<template>
    <div class="ads-management">
      <!-- 搜索区域 -->
      <el-card class="!border-none mb-4" shadow="never">
        <el-form class="mb-[-16px]" :model="queryParams" inline>
            <el-form-item label="广告主ID" prop="ad_account_id">
                    <el-select
                        v-model="queryParams.ad_account_id"
                        filterable
                        remote
                        reserve-keyword
                        placeholder="请选择广告主ID"
                        :remote-method="remoteSearchCorporation"
                        :loading="corporationLoading"
                         style="width: 380px !important;"
                        clearable
                    >
                        <el-option
                            v-for="item in corporationOptions"
                            :key="item.ad_account_id"
                            :label="`${item.ad_account_id}（${item.corporation_name}）`"
                            :value="item.ad_account_id"
                        >
                            <div class="flex flex-col">
                                <span>{{ item.ad_account_id }}</span>
                                <span class="text-gray-400 text-xs">{{ item.corporation_name }}</span>
                            </div>
                        </el-option>
                    <template #footer>
                            <div class="flex justify-between items-center p-2 border-t">
                                <span class="text-sm text-gray-500">共 {{ corporationTotal }} 项</span>
                                <el-pagination
                                    small
                                    layout="prev, pager, next"
                                    :total="corporationTotal"
                                    :page-size="corporationPageSize"
                                    :current-page="corporationCurrentPage"
                                    @current-change="handleCorporationPageChange"
                                />
                            </div>
                    </template>
                 </el-select>
                </el-form-item>
          <el-form-item label="广告名称：">
            <el-input v-model="queryParams.ad_group_name" placeholder="请输入广告名称" clearable />
          </el-form-item>
          <el-form-item label="广告组ID：">
            <el-input v-model="queryParams.ad_group_id" placeholder="请输入广告组ID" clearable />
          </el-form-item>
          <!-- <el-form-item label="广告状态：">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 100px;">
              <el-option label="投放中" value="ADGROUP_STATUS_ACTIVE" />
              <el-option label="部分投放中" value="ADGROUP_STATUS_PARTIAL_ACTIVE" />
              <el-option label="已删除" value="ADGROUP_STATUS_DELETED" />
              <el-option label="创意准备中" value="ADGROUP_STATUS_CREATIVE_EMPTY" />
              <el-option label="创意未投放" value="ADGROUP_STATUS_CREATIVE_STATUS_PENDING" />
              <el-option label="账户余额不足" value="ADGROUP_STATUS_ACCOUNT_BALANCE_NOT_ENOUGH" />
            </el-select>
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" @click="resetPage">搜索</el-button>
            <el-button @click="resetParams">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
  
      <!-- 操作按钮区域 -->
      <div class="operation-area">
        <el-button type="primary" @click="handleAdd">新建广告</el-button>
      </div>
  
      <!-- 列表区域 -->
      <el-card class="!border-none" v-loading="pager.loading" shadow="never">
        <div class="mt-4">
          <el-table :data="tableData" border style="width: 100%">
              <el-table-column label="广告主账户" show-overflow-tooltip width="220">
                          <template #default="scope">
                              <div>{{ scope.row.corporation_name }}</div>
                              <div class="text-gray-400 text-sm mt-1 flex items-center">
                                  <span class="inline-block w-[90px]">ID:</span>
                                  <span>{{ scope.row.ad_account_id }}</span>
                                  <el-icon class="ml-2 cursor-pointer copy-icon" style="color: #4a5dff;" @click="copyToClipboard(scope.row.ad_account_id)">
                                      <CopyDocument />
                                  </el-icon>
                              </div>
                              <div class="text-gray-400 text-sm mt-1 flex items-center">
                                  <span class="inline-block w-[90px]">授权账户ID:</span>
                                  <span>{{ scope.row.account_id }}</span>
                                  <el-icon class="ml-2 cursor-pointer copy-icon" style="color: #4a5dff;" @click="copyToClipboard(scope.row.account_id)">
                                      <CopyDocument />
                                  </el-icon>
                              </div>
                          </template>
                      </el-table-column>
            <el-table-column prop="ad_group_name" label="广告名称" min-width="180" show-overflow-tooltip />
            <el-table-column prop="ad_group_id" label="广告组ID" width="120" show-overflow-tooltip />
            <el-table-column prop="status" label="状态" width="110" align="center">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.system_status)">{{ getStatusText(row.system_status) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="bid_amount" label="出价金额(元)" width="110" align="center">
              <template #default="{ row }">
                {{ (row.bid_amount / 100).toFixed(2) }}
              </template>
            </el-table-column>
            <!-- <el-table-column prop="impressions" label="展示次数" width="120" align="right" /> -->
            <!-- <el-table-column prop="clicks" label="点击次数" width="120" align="right" />
            <el-table-column prop="ctr" label="点击率" width="120" align="right" /> -->
  
            <el-table-column prop="create_time" label="创建时间" width="150" show-overflow-tooltip />
            <el-table-column label="操作" width="280" fixed="right" align="center">
              <template #default="{ row }">
                <div class="operation-buttons">
                  <el-button 
                    link 
                    type="primary" 
                    size="small"
                    :disabled="!hasAdvertiserPermission(row)"
                    @click="handleEdit(row)"
                    :title="getPermissionMessage(row)"
                  >
                    编辑
                  </el-button>
                  <el-button 
                    link 
                    type="primary" 
                    size="small"
                    :disabled="!hasAdvertiserPermission(row)"
                    @click="handleCopy(row)"
                    :title="getPermissionMessage(row)"
                  >
                    复制
                  </el-button>
                  <el-button 
                    link 
                    type="warning" 
                    size="small"
                    :disabled="!hasAdvertiserPermission(row)"
                    @click="handleEditCreative(row)"
                    :title="getPermissionMessage(row)"
                  >
                    编辑创意
                  </el-button>
                  <el-button 
                    link 
                    type="success" 
                    size="small"
                    @click="handleDataAnalysis(row)"
                  >
                    数据分析
                  </el-button>
                  <el-button 
                    link 
                    type="danger" 
                    size="small"
                    @click="handleDelete(row)"
                  >
                    删除
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="flex mt-4 justify-end">
          <pagination v-model="pager" @change="getLists" />
        </div>
      </el-card>
  
      <!-- 新建/编辑对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogType === 'add' ? '新建广告' : '编辑广告'"
        width="80%"
        v-loading="submitLoading"
        element-loading-text="提交中..."
        element-loading-background="rgba(255, 255, 255, 0.8)"
      >
        <el-form 
          :model="formData" 
          :rules="rules"
          ref="formRef"
          label-width="120px" 
          class="ad-form"
        >
          <!-- 营销内容 -->
          <div class="form-section">
            <h3 class="form-section-title" style="font-size: 18px; font-weight: bold;">营销内容</h3>
            <div class="flex gap-4">
              <el-form-item label="广告名称：" prop="ad_group_name" class="flex-1">
                <el-input 
                  v-model="formData.ad_group_name" 
                  placeholder="请输入广告名称" 
                  class="w-full"
                />
              </el-form-item>
  
              <el-form-item label="广告主账号：" prop="id" class="flex-1">
                <el-select 
                  v-model="formData.id"
                  filterable 
                  remote 
                  reserve-keyword 
                  placeholder="请选择广告主账号，可通过广告主id搜索" 
                  :remote-method="remoteSearchAccount" 
                  :loading="accountLoading" 
                  class="w-full"
                  clearable
                  @change="handleAccountChange"
                >
                  <el-option 
                    v-for="item in accountOptions" 
                    :key="String(item.id)" 
                    :label="`${item.corporation_name}【广告主:${item.ad_account_id}】【广告ID:${item.account_id}】`" 
                    :value="String(item.id)"
                  >
                    <div class="flex items-center">
                      <span class="text-base">{{ item.corporation_name }}</span>
                      <span class="text-gray-400 text-sm ml-2">【广告主:{{item.ad_account_id}}】</span>
                      <span class="text-gray-400 text-sm ml-2">【广告ID:{{item.account_id}}】</span>
                    </div>
                  </el-option>
                  <template #footer>
                    <div class="flex justify-between items-center p-2 border-t">
                      <span class="text-sm text-gray-500">共 {{ accountTotal }} 项</span>
                      <el-pagination 
                        small 
                        layout="prev, pager, next" 
                        :total="accountTotal" 
                        :page-size="accountPageSize" 
                        :current-page="accountCurrentPage" 
                        @current-change="handleAccountPageChange" 
                      />
                    </div>
                  </template>
                </el-select>
              </el-form-item>
            </div>
  
            <div class="flex gap-4">
              <el-form-item label="营销目的：" class="flex-1">
                <div class="flex gap-4">
                  <div 
                    v-for="goal in marketingGoals" 
                    :key="goal.value"
                    class="goal-item cursor-pointer"
                    :class="{ 
                      'active': formData.marketing_goal === goal.value,
                      'disabled': !formData.ad_account_id 
                    }"
                    @click="handleMarketingGoalClick(goal.value)"
                  >
                    <div class="goal-card">
                      <el-icon class="mb-1"><component :is="goal.icon" /></el-icon>
                      <div class="text-sm">{{ goal.label }}</div>
                    </div>
                  </div>
                </div>
                <!-- 提示信息 -->
                <div v-if="!formData.ad_account_id" class="mt-2 text-sm text-gray-500">
                  请先选择广告主账号
                </div>
              </el-form-item>
            </div>
  
            <div class="flex flex-col lg:flex-row gap-4">
              <el-form-item label="推广产品：" prop="marketing_target_type" class="!mb-2 lg:!mb-4 w-full lg:w-1/2">
                <template v-if="!formData.ad_account_id">
                  <div class="text-gray-400 text-sm pl-2">请先选择广告主账号</div>
                </template>
                <el-radio-group 
                  v-else
                  v-model="formData.marketing_target_type" 
                  class="w-full flex flex-wrap gap-2"
                >
                  <el-radio 
                    v-for="(label, value) in marketingTargetTypes" 
                    :key="value" 
                    :label="value"
                    class="!mr-0 flex-shrink-0"
                  >
                    {{ label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
  
              <el-form-item label="产品列表：" prop="target_asset_id" class="!mb-2 lg:!mb-4 w-full lg:w-1/2">
                <el-select 
                  v-model="formData.target_asset_id" 
                  placeholder="先选择推广产品，再选择产品列表" 
                  :loading="targetAssetLoading" 
                  class="w-full"
                  clearable
                  :disabled="!formData.ad_account_id || !formData.marketing_target_type || accountLoading"
                  popper-class="product-select-dropdown"
                  @change="handleTargetAssetChange"
                >
                  <el-option 
                    v-for="item in targetAssetOptions" 
                    :key="item.marketing_asset_id" 
                    :label="item.marketing_asset_name" 
                    :value="String(item.marketing_asset_id)"
                  >
                    <div class="flex items-center w-full">
                      <span class="truncate flex-1">{{ item.marketing_asset_name }}</span>
                      <span class="text-gray-400 text-xs ml-2 truncate flex-1">{{ item.description }}</span>
                    </div>
                  </el-option>
                </el-select>
              </el-form-item>
            </div>
  
            <div class="flex gap-4">
              <el-form-item label="优化目标：" prop="optimization_goal" class="w-[calc(50%-8px)]">
                <el-select 
                  v-model="formData.optimization_goal" 
                  class="w-full"
                  placeholder="请选择优化目标"
                  :loading="optimizationGoalLoading"
                  :disabled="!formData.ad_account_id || !formData.marketing_goal || !formData.marketing_target_type"
                >
                  <el-option
                    v-for="item in optimizationGoals"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </div>
  
            <!-- <el-form-item label="广告描述" class="w-full">
              <el-input
                v-model="formData.description"
                type="textarea"
                placeholder="请输入广告描述"
                class="w-full"
              />
            </el-form-item> -->
          </div>
  
          <!-- 广告版位 -->
          <div class="form-section">
            <h3 class="form-section-title" style="font-size: 18px; font-weight: bold;">广告版位</h3>
            <el-form-item label="投放位置：">
              <el-radio-group v-model="formData.positionType" class="mb-4">
                <el-radio label="auto">自动版位</el-radio>
                <el-radio label="specific">特定版位</el-radio>
              </el-radio-group>
  
              <el-select
                v-if="formData.positionType === 'specific'"
                v-model="formData.position"
                multiple
                placeholder="请选择特定版位"
                class="w-full"
              >
                <el-option label="微信视频号" value="video" />
                <el-option label="微信朋友圈" value="moments" />
                <el-option label="微信公众号与小程序" value="mp" />
                <el-option label="腾讯平台与内容媒体" value="tencent" />
                <el-option label="优量汇" value="union" />
              </el-select>
            </el-form-item>
          </div>
  
          <!-- 定向设置 -->
          <div class="form-section">
            <h3 class="form-section-title" style="font-size: 18px; font-weight: bold;">定向设置</h3>
            <div class="flex flex-wrap gap-4">
              <el-form-item label="地域：" class="w-[calc(50%-8px)]" >
                <el-radio-group v-model="regionType" class="mb-4 w-full">
                  <el-radio label="all">不限</el-radio>
                  <el-radio label="region">区域</el-radio>
                </el-radio-group>
              
              </el-form-item>
              <el-form-item label="性别：" class="w-[calc(50%-8px)]">
                  <el-radio-group v-model="formData.gender" class="w-full mb-4">
                    <el-radio label="ALL">不限</el-radio>
                    <el-radio label="MALE">男</el-radio>
                    <el-radio label="FEMALE">女</el-radio>
                  </el-radio-group>
                </el-form-item>
            </div>
              <div v-if="regionType === 'region'" class="w-full mb-4">
                <el-form-item label="地区选择：" class="w-full">
                  <el-select 
                    v-model="selectedProvince" 
                    multiple 
                    filterable 
                    clearable
                    placeholder="请选择省份" 
                    :loading="regionLoading" 
                    style="width: 32%; margin-right: 2%;"
                    :popper-class="'region-select-dropdown'"
                  >
                    <el-option v-for="item in provinceOptions" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                  <el-select 
                    v-model="selectedCity" 
                    multiple 
                    filterable 
                    clearable
                    placeholder="请选择城市" 
                    :loading="regionLoading" 
                    :disabled="!selectedProvince.length" 
                    style="width: 32%;margin-right: 2%;"
                    :popper-class="'region-select-dropdown'"
                  >
                    <el-option v-for="item in cityOptions" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                  <el-select 
                    v-model="selectedDistrict" 
                    multiple 
                    filterable 
                    clearable
                    placeholder="请选择区县" 
                    :loading="regionLoading" 
                    :disabled="!selectedCity.length" 
                    style="width: 32%;"
                    :popper-class="'region-select-dropdown'"
                  >
                    <el-option v-for="item in districtOptions" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item>
              </div>
              <div class="w-full mb-4">
                <el-form-item label="年龄：" class="w-full">
                  <div class="flex items-center gap-4 age-align-fix">
                    <el-radio-group v-model="ageType">
                      <el-radio label="all">不限</el-radio>
                      <el-radio label="custom">自定义</el-radio>
                    </el-radio-group>
                
                    <el-checkbox-group v-if="ageType === 'custom'" v-model="formData.age" class="age-checkbox-group">
                        <el-checkbox v-for="item in ageOptions" :key="item.value" :label="item.value">
                            {{ item.label }}
                        </el-checkbox>
                    </el-checkbox-group>
                  </div>
                </el-form-item>
              </div>

              <!-- 自定义人群设置 -->
              <div class="w-full mb-4 pt-4">
                <el-form-item label="自定义人群：" class="w-full">
                  <div class="flex  gap-4">
                    <div class="flex items-center gap-4">
                      <el-radio-group v-model="customAudienceType">
                        <el-radio label="all">不限</el-radio>
                        <el-radio label="target">定向人群</el-radio>
                        <el-radio label="exclude">非定向人群</el-radio>
                      </el-radio-group>
                    </div>
                    
                    <!-- 定向人群选择 -->
                    <div v-if="customAudienceType === 'target'" class="flex items-center gap-4">
                      <el-select
                        v-model="formData.custom_audience"
                        multiple
                        filterable
                        remote
                        clearable
                        reserve-keyword
                        placeholder="请选择定向人群"
                        :remote-method="remoteSearchCustomAudience"
                        :loading="customAudienceLoading"
                        class="w-full custom-audience-select"
                        no-data-text="⚠️ 暂无自定义人群数据，请先创建自定义人群"
                        no-match-text="未找到匹配的自定义人群"
                        @focus="handleCustomAudienceFocus"
                      >
                        <el-option
                          v-for="item in customAudienceOptions"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"
                        >
                          <div class="flex items-center justify-between">
                            <span>{{ item.name }}</span>
                            <!-- <span class="text-gray-400 text-xs">{{ item.description }}</span> -->
                          </div>
                        </el-option>
                      </el-select>
                    </div>
                    
                    <!-- 非定向人群选择 -->
                    <div v-if="customAudienceType === 'exclude'" class="w-[calc(50%-8px)]">
                      <el-select
                        v-model="formData.excluded_custom_audience"
                        multiple
                        filterable
                        remote
                        clearable
                        reserve-keyword
                        placeholder="请选择非定向人群"
                        :remote-method="remoteSearchCustomAudience"
                        :loading="customAudienceLoading"
                        class="w-full custom-audience-select"
                        no-data-text="⚠️ 暂无自定义人群数据，请先创建自定义人群"
                        no-match-text="未找到匹配的自定义人群"
                        @focus="handleCustomAudienceFocus"
                      >
                        <el-option
                          v-for="item in customAudienceOptions"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"
                        >
                          <div class="flex items-center justify-between">
                            <span>{{ item.name }}</span>
                            <span class="text-gray-400 text-xs">{{ item.description }}</span>
                          </div>
                        </el-option>
                      </el-select>
                    </div>
                  </div>
            
                </el-form-item>
              </div>
          </div>
  
          <!-- 出价与预算 -->
          <div class="form-section">
              <h3 class="form-section-title" style="font-size: 18px; font-weight: bold;">出价与预算</h3>
            <div class="flex flex-wrap gap-4">
              <el-form-item label="出价方式：" prop="bid_type" class="w-[calc(50%-8px)]">
                <el-select v-model="formData.bid_type" placeholder="请选择出价方式" class="w-full">
                  <el-option label="OCPM" :value="BidType.OCPM" />
                  <!-- <el-option label="CPM" :value="BidType.CPM" /> -->
                  <!-- <el-option label="CPD" :value="BidType.CPD" /> -->
                </el-select>
              </el-form-item>
  
              <el-form-item label="出价金额(元)：" prop="bid_amount" class="w-[calc(50%-8px)]">
                <el-input-number v-model="formData.bid_amount" :min="0.01" :precision="2" class="w-full" :step="0.01" />
              </el-form-item>
  
              <!-- <el-form-item label="日预算(分)" class="w-[calc(50%-8px)]">
                <el-input-number v-model="formData.daily_budget" :min="0" :precision="2" class="w-full" :step="0.01" />
              </el-form-item> -->
            </div>
          </div>
  
          <!-- 广告设置 -->
          <div class="form-section">
            <h3 class="form-section-title" style="font-size: 18px; font-weight: bold;">广告设置</h3>
            <div class="flex flex-wrap gap-4">
              <el-form-item label="投放时间：" prop="startTime" class="w-[calc(50%-8px)]">
                <div class="flex items-center gap-2">
                  <el-date-picker
                    v-model="formData.startTime"
                    type="date"
                    placeholder="开始时间"
                    class="w-[calc(50%-4px)]"
                    :disabled-date="(time: Date) => {
                      const today = new Date()
                      today.setHours(0, 0, 0, 0)
                      if (formData.endTime) {
                        return time > formData.endTime || time < today
                      }
                      return time < today
                    }"
                    @change="(val: Date | null) => {
                      if (val && formData.endTime && val > formData.endTime) {
                        formData.endTime = val
                      }
                    }"
                  />
                  <span>至</span>
                  <el-date-picker
                    v-model="formData.endTime"
                    type="date"
                    placeholder="结束时间"
                    class="w-[calc(50%-4px)]"
                    :disabled-date="(time: Date) => {
                      const today = new Date()
                      today.setHours(0, 0, 0, 0)
                      if (formData.startTime) {
                        return time < formData.startTime
                      }
                      return time < today
                    }"
                    @change="(val: Date | null) => {
                      if (val && formData.startTime && val < formData.startTime) {
                        ElMessage.warning('结束时间不能小于开始时间')
                        formData.endTime = formData.startTime
                      }
                    }"
                  />
                </div>
              </el-form-item>
  <!-- 
              <el-form-item label="投放时段" class="w-[calc(50%-8px)]">
                <el-time-picker
                  v-model="formData.timeRange"
                  is-range
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  class="w-full"
                />
              </el-form-item> -->
            </div>
          </div>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
          </span>
        </template>
      </el-dialog>
  
      <!-- 数据分析弹框 -->
      <el-dialog
        v-model="dataAnalysisDialogVisible"
        title="数据分析"
        width="900px"
        :close-on-click-modal="false"
        v-loading="dataAnalysisLoading"
      >
        <div v-if="dataAnalysisData && !dataAnalysisLoading" class="data-analysis-content">
          <div class="analysis-header">
            <h3 class="analysis-title">{{ dataAnalysisData.ad_group_name || '广告数据分析' }}</h3>
            <p class="analysis-subtitle">数据统计时间：{{ dataAnalysisData.date_range || '最近30天' }}</p>
          </div>
          
          <div class="analysis-grid">
            <div class="analysis-card">
              <div class="card-header">
                <el-icon class="card-icon"><View /></el-icon>
                <span class="card-title">曝光次数</span>
              </div>
              <div class="card-value">{{ formatNumber(dataAnalysisData.view_count) }}</div>
              <div class="card-trend" v-if="dataAnalysisData.view_count_trend">
                <span :class="dataAnalysisData.view_count_trend > 0 ? 'trend-up' : 'trend-down'">
                  {{ dataAnalysisData.view_count_trend > 0 ? '+' : '' }}{{ dataAnalysisData.view_count_trend }}%
                </span>
              </div>
            </div>
            
            <div class="analysis-card">
              <div class="card-header">
                <el-icon class="card-icon"><Mouse /></el-icon>
                <span class="card-title">点击次数</span>
              </div>
              <div class="card-value">{{ formatNumber(dataAnalysisData.valid_click_count) }}</div>
              <div class="card-trend" v-if="dataAnalysisData.valid_click_count_trend">
                <span :class="dataAnalysisData.valid_click_count_trend > 0 ? 'trend-up' : 'trend-down'">
                  {{ dataAnalysisData.valid_click_count_trend > 0 ? '+' : '' }}{{ dataAnalysisData.valid_click_count_trend }}%
                </span>
              </div>
            </div>
            
            <div class="analysis-card">
              <div class="card-header">
                <el-icon class="card-icon"><TrendCharts /></el-icon>
                <span class="card-title">点击率</span>
              </div>
              <div class="card-value">{{ dataAnalysisData.ctr }}</div>
              <div class="card-trend" v-if="dataAnalysisData.ctr_trend">
                <span :class="dataAnalysisData.ctr_trend > 0 ? 'trend-up' : 'trend-down'">
                  {{ dataAnalysisData.ctr_trend > 0 ? '+' : '' }}{{ dataAnalysisData.ctr_trend }}%
                </span>
              </div>
            </div>
            
            <div class="analysis-card">
              <div class="card-header">
                <el-icon class="card-icon"><Money /></el-icon>
                <span class="card-title">点击均价</span>
              </div>
              <div class="card-value">¥{{ formatPrice(dataAnalysisData.cpc) }}</div>
              <div class="card-trend" v-if="dataAnalysisData.cpc_trend">
                <span :class="dataAnalysisData.cpc_trend > 0 ? 'trend-down' : 'trend-up'">
                  {{ dataAnalysisData.cpc_trend > 0 ? '+' : '' }}{{ dataAnalysisData.cpc_trend }}%
                </span>
              </div>
            </div>
            
            <div class="analysis-card">
              <div class="card-header">
                <el-icon class="card-icon"><Wallet /></el-icon>
                <span class="card-title">花费</span>
              </div>
              <div class="card-value">¥{{ formatPrice(dataAnalysisData.cost) }}</div>
              <div class="card-trend" v-if="dataAnalysisData.cost_trend">
                <span :class="dataAnalysisData.cost_trend > 0 ? 'trend-up' : 'trend-down'">
                  {{ dataAnalysisData.cost_trend > 0 ? '+' : '' }}{{ dataAnalysisData.cost_trend }}%
                </span>
              </div>
            </div>
            
            <div class="analysis-card">
              <div class="card-header">
                <el-icon class="card-icon"><User /></el-icon>
                <span class="card-title">目标转化量</span>
              </div>
              <div class="card-value">{{ formatNumber(dataAnalysisData.conversions_count) }}</div>
              <div class="card-trend" v-if="dataAnalysisData.conversions_count_trend">
                <span :class="dataAnalysisData.conversions_count_trend > 0 ? 'trend-up' : 'trend-down'">
                  {{ dataAnalysisData.conversions_count_trend > 0 ? '+' : '' }}{{ dataAnalysisData.conversions_count_trend }}%
                </span>
              </div>
            </div>
            
            <div class="analysis-card">
              <div class="card-header">
                <el-icon class="card-icon"><Coin /></el-icon>
                <span class="card-title">目标转化成本</span>
              </div>
              <div class="card-value">¥{{ formatPrice(dataAnalysisData.conversions_cost) }}</div>
              <div class="card-trend" v-if="dataAnalysisData.conversions_cost_trend">
                <span :class="dataAnalysisData.conversions_cost_trend > 0 ? 'trend-down' : 'trend-up'">
                  {{ dataAnalysisData.conversions_cost_trend > 0 ? '+' : '' }}{{ dataAnalysisData.conversions_cost_trend }}%
                </span>
              </div>
            </div>
          </div>
          
          <div class="analysis-summary">
            <h4>数据摘要</h4>
            <div class="summary-content">
              <p>• 总曝光次数：{{ formatNumber(dataAnalysisData.view_count) }} 次</p>
              <p>• 总点击次数：{{ formatNumber(dataAnalysisData.valid_click_count) }} 次</p>
              <p>• 平均点击率：{{ dataAnalysisData.ctr }}</p>
              <p>• 总花费：¥{{ formatPrice(dataAnalysisData.cost) }}</p>
              <p>• 转化量：{{ formatNumber(dataAnalysisData.conversions_count) }} 次</p>
              <p>• 平均转化成本：¥{{ formatPrice(dataAnalysisData.conversions_cost) }}</p>
            </div>
          </div>
        </div>
        
        <div v-else-if="!dataAnalysisLoading && !dataAnalysisData" class="no-data">
          <el-empty description="暂无数据" />
        </div>
        
        <!-- 加载状态显示 -->
        <div v-if="dataAnalysisLoading" class="loading-content">
          <div class="loading-spinner">
            <el-icon class="is-loading"><Loading /></el-icon>
            <p>正在加载数据分析...</p>
          </div>
        </div>
        
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dataAnalysisDialogVisible = false">关闭</el-button>
            <el-button 
              type="primary" 
              :loading="dataAnalysisLoading"
              @click="refreshDataAnalysis"
            >
              {{ dataAnalysisLoading ? '刷新中...' : '刷新数据' }}
            </el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 添加复制弹框 -->
      <el-dialog
        v-model="copyDialogVisible"
        title="复制广告"
        width="700px"
        :close-on-click-modal="false"
      >
        <el-form :model="copyForm" label-width="100px">
          <el-form-item label="广告名称" required>
            <el-input v-model="copyForm.ad_group_name" placeholder="请输入广告名称" />
          </el-form-item>
          <el-form-item label="投放时间" required>
            <div class="flex items-center gap-2">
              <el-date-picker
                v-model="copyForm.startTime"
                type="date"
                placeholder="开始时间"
                class="w-[calc(50%-4px)]"
                :disabled-date="(time: Date) => {
                  const today = new Date()
                  today.setHours(0, 0, 0, 0)
                  if (copyForm.endTime) {
                    return time > copyForm.endTime || time < today
                  }
                  return time < today
                }"
                @change="(val: Date | null) => {
                  if (val && copyForm.endTime && val > copyForm.endTime) {
                    copyForm.endTime = val
                  }
                }"
              />
              <span>至</span>
              <el-date-picker
                v-model="copyForm.endTime"
                type="date"
                placeholder="结束时间"
                class="w-[calc(50%-4px)]"
                :disabled-date="(time: Date) => {
                  const today = new Date()
                  today.setHours(0, 0, 0, 0)
                  if (copyForm.startTime) {
                    return time < copyForm.startTime
                  }
                  return time < today
                }"
                @change="(val: Date | null) => {
                  if (val && copyForm.startTime && val < copyForm.startTime) {
                    ElMessage.warning('结束时间不能小于开始时间')
                    copyForm.endTime = copyForm.startTime
                  }
                }"
              />
            </div>
          </el-form-item>
          <el-form-item label="选择账号" required>
            <el-select
              v-model="copyForm.selectedIds"
              multiple
              filterable
              remote
              clearable
              reserve-keyword
              placeholder="请选择要复制到的账号"
              :remote-method="copyRemoteSearchAccount"
              :loading="copyAccountLoading"
              class="w-full"
              no-data-text="暂无数据"
              no-match-text="暂无匹配数据"
            >
              <!-- 加载状态显示 -->
              <template v-if="copyAccountLoading">
                <div class="flex items-center justify-center py-4 text-gray-400">
                  <el-icon class="mr-2 animate-spin"><Loading /></el-icon>
                  <span>正在加载账号数据...</span>
                </div>
              </template>
              
              <el-option
                v-for="item in copyAccountOptions"
                :key="String(item.id)"
                :label="`${item.corporation_name}【广告主:${item.ad_account_id}】【广告ID:${item.account_id}】`"
                :value="String(item.id)"
              >
                <div class="flex items-center">
                  <span class="text-base">{{ item.corporation_name }}</span>
                  <span class="text-gray-400 text-sm ml-2">【广告主:{{item.ad_account_id}}】</span>
                  <span class="text-gray-400 text-sm ml-2">【广告ID:{{item.account_id}}】</span>
                </div>
              </el-option>
              <!-- 当没有数据时显示提示 -->
              <template v-if="!copyAccountLoading && copyAccountOptions.length === 0">
                <div class="flex flex-col items-center justify-center py-6 text-gray-400">
                  <el-icon class="mb-2 text-2xl"><User /></el-icon>
                  <span class="text-sm mb-1">暂无可用账号数据</span>
                  <span class="text-xs text-gray-300">请尝试搜索其他关键词或联系管理员</span>
                </div>
              </template>
              <template #footer>
                <div class="flex flex-col gap-2 p-2 border-t">
                  <div class="flex justify-between items-center">
                    <el-checkbox 
                      v-model="copySelectAll" 
                      @change="handleCopySelectAll"
                      :indeterminate="copySelectIndeterminate"
                      :disabled="copyAccountOptions.length === 0"
                    >
                      全选
                    </el-checkbox>
                    <span class="text-sm text-gray-500">共 {{ copyAccountTotal }} 项</span>
                  </div>
                  <el-pagination
                    v-if="copyAccountTotal > 0"
                    small
                    layout="prev, pager, next"
                    :total="copyAccountTotal"
                    :page-size="copyAccountPageSize"
                    :current-page="copyAccountCurrentPage"
                    @current-change="copyHandleAccountPageChange"
                  />
                </div>
              </template>
            </el-select>
            <!-- 添加使用提示 -->
            <div class="text-xs text-gray-400 mt-1">
              💡 提示：可以通过账号ID关键词搜索账号
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="copyDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmCopy" :loading="copyLoading">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 添加创意跳转弹框 -->
      <el-dialog
        v-model="creativeJumpDialogVisible"
        title="创意跳转"
        width="700px"
        :close-on-click-modal="false"
      >
                 <div class="jump-content">
           <p><strong>🎉 广告创建成功！</strong></p>
           <p>您可以选择跳转到创意新增页面，为这个广告创建创意内容。</p>
           <div style="background: #f0f9ff; border: 1px solid #bae6fd; border-radius: 8px; padding: 16px; margin: 16px 0;">
             <p style="margin: 0 0 12px 0; color: #0369a1; font-weight: 600;">📋 广告信息</p>
             <ul style="margin: 0; padding-left: 20px;">
               <li><strong>广告名称：</strong>{{ currentCreatedAd?.ad_group_name }}</li>
               <li><strong>广告组ID：</strong>{{ currentCreatedAd?.ad_group_id }}</li>
               <li><strong>广告主账号：</strong>{{ currentCreatedAd?.corporation_name }}</li>
               <li><strong>广告ID：</strong>{{ currentCreatedAd?.account_id }}</li>
             </ul>
           </div>
           <p style="color: #059669; font-size: 14px;">💡 提示：点击确定将自动跳转到创意新增页面，并自动填充广告组信息</p>
         </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="creativeJumpDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmJump" :loading="creativeJumpLoading">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 创意选择弹框 -->
      <el-dialog
        v-model="creativeSelectDialogVisible"
        title="选择创意"
        width="900px"
        :close-on-click-modal="false"
        v-loading="creativeListLoading"
      >
        <div class="creative-select-content">
          <div class="mb-4">
            <p><strong>📋 当前广告信息</strong></p>
            <div style="background: #f0f9ff; border: 1px solid #bae6fd; border-radius: 8px; padding: 16px; margin: 16px 0;">
              <ul style="margin: 0; padding-left: 20px;">
                <li><strong>广告名称：</strong>{{ currentAdForCreative?.ad_group_name }}</li>
                <li><strong>广告组ID：</strong>{{ currentAdForCreative?.ad_group_id }}</li>
                <li><strong>广告主账号：</strong>{{ currentAdForCreative?.corporation_name }}</li>
                <li><strong>广告ID：</strong>{{ currentAdForCreative?.account_id }}</li>
              </ul>
            </div>
            <p style="color: #059669; font-size: 14px;">💡 请选择要编辑的创意，选择后将跳转到创意编辑页面</p>
          </div>
          
          <div class="creative-list">
            <el-table 
              :data="creativeList" 
              @row-click="handleCreativeSelect"
              style="width: 100%"
              :row-class-name="getCreativeRowClass"
            >
              <el-table-column label="创意名称" prop="dynamic_creative_name" show-overflow-tooltip />
              <el-table-column label="创意状态" width="120" align="center">
                <template #default="{ row }">
                  <el-tag 
                    v-if="row.creative_set_approval_status"
                    :type="getCreativeStatusType(row.creative_set_approval_status)" 
                    size="small"
                  >
                    {{ getCreativeStatusText(row.creative_set_approval_status) }}
                  </el-tag>
                  <span v-else class="text-gray-400">-</span>
                </template>
              </el-table-column>
              <el-table-column label="创建时间" prop="create_time" width="150" show-overflow-tooltip>
                <template #default="{ row }">
                  {{ formatCreativeTime(row.create_time) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100" align="center">
                <template #default="{ row }">
                  <el-button 
                    type="primary" 
                    size="small"
                    :loading="creativeJumpLoading"
                    @click.stop="handleCreativeSelect(row)"
                  >
                    选择
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            
            <div v-if="creativeList.length === 0 && !creativeListLoading" class="no-data">
              <el-empty description="暂无创意数据" />
            </div>
          </div>
        </div>
        
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="creativeSelectDialogVisible = false">取消</el-button>
            <el-button 
              type="primary" 
              @click="handleCreateNewCreative"
              :loading="creativeJumpLoading"
            >
              新建创意
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, reactive, computed, onMounted, watch, nextTick, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import type { FormItemRule, CheckboxValueType } from 'element-plus'
import type { AdListItem, AdFormData, SearchForm } from '@/types/ads'
import { AdStatus, BidType, AdPosition } from '@/types/ads'
import { usePaging } from '@/hooks/usePaging'
import { getAdsList, createAd, updateAd, deleteAd, getAdDetail, get_targeting_tags,
     get_target_assets, get_target_targets, get_optimization_goal_permissions, copyAd, getCorporationList, get_custom_audience, getAdReport } from '@/api/ads'
import { apiGetAccounts, apiTencentAdCreativityList } from '@/api/tencent_ad_creativity'
import { CopyDocument, ShoppingBag, Promotion, ChatDotRound, Money, User, Loading, View, Mouse, TrendCharts, Wallet, Coin } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
  
  // 日期格式化函数
  const formatDate = (date: Date): string => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  }
  
  interface AccountOption {
      id: string | number;
      ad_account_id: string;
      account_id: string;
      corporation_name: string;
      // ... 其他字段
  }
  
  interface RegionOption {
      id: string;
      name: string;
      children?: RegionOption[];
  }
  
  interface TargetAssetOption {
    marketing_asset_id: string;
    marketing_asset_name: string;
    description: string;
  }

  // 自定义人群选项
  interface CustomAudienceOption {
    id: string;
    name: string;
    description: string;
  }
  
  // 广告主名称下拉选项
  interface CorporationOption {
    ad_account_id: string;
    corporation_name: string;
  }
  
  const corporationOptions = ref<CorporationOption[]>([])
  const corporationLoading = ref(false)
  const corporationTotal = ref(0)
  const corporationCurrentPage = ref(1)
  const corporationPageSize = ref(10)
  const corporationKeyword = ref('')
  
  // 查询条件
  const queryParams = reactive({
      ad_group_name: '',
      ad_group_id: '',
      status: '',
      ad_account_id:''
  })
  
  // 分页相关
  const { pager, getLists, resetPage, resetParams } = usePaging({
      fetchFun: getAdsList,
      params: queryParams
  })
  
  // 表格数据
  const tableData = computed(() => pager.lists)
  
  // 对话框相关
  const dialogVisible = ref(false)
  const dialogType = ref<'add' | 'edit'>('add')
  const activeTab = ref('content')
  const currentAdId = ref('')
  
  // 广告主账号相关
  const accountOptions = ref<AccountOption[]>([])
  const accountLoading = ref(false)
  const accountTotal = ref(0)
  const accountCurrentPage = ref(1)
  const accountPageSize = ref(10)
  const accountKeyword = ref('')
  
  // 区域选择相关
  const regionType = ref('all') // 'all' | 'region'
  
  // 第三方资产相关
  const targetAssetOptions = ref<TargetAssetOption[]>([])
  const targetAssetLoading = ref(false)
  const targetAssetKeyword = ref('')
  
  // 营销目标类型
  interface MarketingTargetType {
    [key: string]: string;
  }
  
  // 区域选择相关
  const regionLoading = ref(false)
  const provinceOptions = ref<RegionOption[]>([])
  const cityOptions = ref<RegionOption[]>([])
  const districtOptions = ref<RegionOption[]>([])
  const selectedProvince = ref<string[]>([])
  const selectedCity = ref<string[]>([])
  const selectedDistrict = ref<string[]>([])
  
  // 营销目标类型选项
  const marketingTargetTypes = ref<MarketingTargetType>({})
  const marketingTargetTypeLoading = ref(false)
  
  // 获取营销目标类型
  const fetchMarketingTargetTypes = async () => {
    console.log(formData.marketing_target_type,'marketing_target_type1111222')
    if (!formData.marketing_goal) {
      marketingTargetTypes.value = {}
      // 只在新建时清空，编辑时保持原有值
      if (dialogType.value === 'add') {
        formData.marketing_target_type = ''
      }
      return
    }

    // 如果正在加载，先取消之前的请求
    if (marketingTargetTypeLoading.value) {
      console.log('取消之前的营销目标类型请求')
      return
    }
    console.log(formData.marketing_target_type,'marketing_target_type11111112')

    marketingTargetTypeLoading.value = true
    try {
      console.log('开始获取营销目标类型，marketing_goal:', formData.marketing_goal)
      const res = await get_target_targets({
        ad_account_id: formData.ad_account_id,
        account_id: formData.account_id
      })
      console.log('获取推广产品类型结果:', res)
      if (res) {
        // 将key和value数组合并成对象
        const types: MarketingTargetType = {}
        res.key.forEach((key: string, index: number) => {
          types[key] = res.value[index]
        })
        marketingTargetTypes.value = types
        console.log(formData.marketing_target_type,'marketing_target_type11111')

        // 编辑时：如果当前选中的值在新的选项中，保持选择；否则清空
        if (dialogType.value === 'edit') {
        console.log(formData.marketing_target_type,'marketing_target_type1111')

            console.log(formData.marketing_target_type,'formData.marketing_target_typeformData.marketing_target_type')
          if (formData.marketing_target_type && !Object.keys(types).includes(formData.marketing_target_type)) {
            console.warn('当前选择的营销目标类型不在可用选项中，已清空选择')
            formData.marketing_target_type = ''
            formData.target_asset_id = '' // 同时清空产品选择
          }
        } else {
          // 新建时：如果当前选中的值不在新的选项中，清空选择
          if (formData.marketing_target_type && !Object.keys(types).includes(formData.marketing_target_type)) {
            formData.marketing_target_type = ''
          }
        }
        
        console.log('营销目标类型已更新:', marketingTargetTypes.value)
      } else {
        marketingTargetTypes.value = {}
        // 只在新建时清空，编辑时保持原有值
        if (dialogType.value === 'add') {
          formData.marketing_target_type = ''
        }
      }
    } catch (error: any) {
      // 如果是取消请求的错误，不显示错误信息
      if (error.name === 'CanceledError' || error.code === 'ERR_CANCELED') {
        console.log('营销目标类型请求已取消')
        return
      }
      
      console.error('获取营销目标类型失败：', error)
      ElMessage.error({
        message: error.response?.data?.message || '获取营销目标类型失败',
        duration: 15000
      })
      marketingTargetTypes.value = {}
      // 只在新建时清空，编辑时保持原有值
      if (dialogType.value === 'add') {
        formData.marketing_target_type = ''
      }
    } finally {
      marketingTargetTypeLoading.value = false
    }
  }
  
  // 监听区域类型变化
  watch(regionType, (newVal) => {
      if (newVal === 'all') {
          selectedProvince.value = []
          selectedCity.value = []
          selectedDistrict.value = []
          formData.region = []
      } else {
          fetchProvinceOptions()
      }
  })
  
  // 表单数据
  const formData = reactive<AdFormData & { 
      id: string;
      ad_account_id: string;
      account_id: string;
      corporation_name: string;
      ad_group_id: string;
      positionType: 'auto' | 'specific';
      gender: 'ALL' | 'MALE' | 'FEMALE';
      person_type: string[];
      marketing_goal: 'MARKETING_GOAL_LEAD_RETENTION'|'MARKETING_GOAL_BRAND_PROMOTION';
      target_asset_id: string;
      optimization_goal: string;
      marketing_target_type: string;
      custom_audience: string[];
      excluded_custom_audience: string[];
  }>({
      id: '',
      ad_account_id: '',
      account_id: '',
      corporation_name: '',
      ad_group_id: '',
      positionType: 'auto',
      gender: 'ALL',
      person_type: ['LIVE_IN'],
      marketing_goal: 'MARKETING_GOAL_LEAD_RETENTION',
      target_asset_id: '',
      optimization_goal: '',
      marketing_target_type: '',
      custom_audience: [],
      excluded_custom_audience: [],
      ad_group_name: '',
      description: '',
      position: [],
      region: [],
      age: [],
      bid_type: BidType.OCPM,
      bid_amount: 0,
      daily_budget: 0,
      startTime: undefined,
      endTime: undefined,
      timeRange: undefined
  })
  
  // 获取状态类型
  const getStatusType = (status: string) => {
      const map: Record<string, 'success' | 'warning' | 'info' | 'danger'> = {
          'ADGROUP_STATUS_ACTIVE': 'success',
          'ADGROUP_STATUS_PARTIAL_ACTIVE': 'success',
          'ADGROUP_STATUS_DELETED': 'info',
          'ADGROUP_STATUS_CREATIVE_EMPTY': 'warning',
          'ADGROUP_STATUS_CREATIVE_STATUS_PENDING': 'warning',
          'ADGROUP_STATUS_ACCOUNT_BALANCE_NOT_ENOUGH': 'danger'
      }
      return map[status] || 'success'
  }
  
  // 获取状态文本
  const getStatusText = (status: string) => {
      const map: Record<string, string> = {
          'ADGROUP_STATUS_ACTIVE': '投放中',
          'ADGROUP_STATUS_PARTIAL_ACTIVE': '部分投放中',
          'ADGROUP_STATUS_DELETED': '已删除',
          'ADGROUP_STATUS_CREATIVE_EMPTY': '创意准备中',
          'ADGROUP_STATUS_CREATIVE_STATUS_PENDING': '创意未投放',
          'ADGROUP_STATUS_ACCOUNT_BALANCE_NOT_ENOUGH': '账户余额不足'
      }
      return map[status] || '投放中'
  }
  
  // 远程搜索广告主账号
  const remoteSearchAccount = (query: string) => {
    console.log(query,'queryqueryqueryquery')
      accountKeyword.value = query
      accountCurrentPage.value = 1
      fetchAccountOptions()
  }
  
  // 获取广告主账号选项
  const fetchAccountOptions = async () => {
      accountLoading.value = true
      try {
          const params = {
              account_role_type: "ACCOUNT_ROLE_TYPE_ADVERTISER",
              page_no: accountCurrentPage.value,
              page_size: accountPageSize.value,
              ad_account_id: accountKeyword.value//搜索条件
          }    
          const res= await apiGetAccounts(params)
          if (res.list) {
              accountOptions.value = res.list || []
              accountTotal.value = res.total || 0
          } else {
              ElMessage.error('获取广告主账号列表失败')
              accountOptions.value = []
              accountTotal.value = 0
          }
      } catch (error) {
          console.error('获取广告主账号列表失败：', error)
          ElMessage.error('获取广告主账号列表失败')
          accountOptions.value = []
          accountTotal.value = 0
      } finally {
          accountLoading.value = false
      }
  }
  
  // 处理广告主账号分页变化
  const handleAccountPageChange = (page: number) => {
      accountCurrentPage.value = page
      fetchAccountOptions()
  }
  
  // 重置表单数据
  const resetFormData = () => {
      if (!formRef.value) return
      formRef.value.resetFields()
      Object.assign(formData, {
          id: '',
          ad_account_id: '',
          account_id: '',
          corporation_name: '',
          ad_group_id: '',
          positionType: 'auto',
          gender: 'ALL',
          person_type: ['LIVE_IN'],
          marketing_goal: 'MARKETING_GOAL_LEAD_RETENTION',
          target_asset_id: '',
          optimization_goal: '',
          marketing_target_type: '',
          custom_audience: [],
          excluded_custom_audience: [],
          ad_group_name: '',
          description: '',
          position: [],
          region: [],
          age: [],
          bid_type: BidType.OCPM,
          bid_amount: 0,
          daily_budget: 0,
          startTime: undefined,
          endTime: undefined,
          timeRange: undefined
      })
      regionType.value = 'all'
      ageType.value = 'all'
      customAudienceType.value = 'all'
  }
  
  /**
   * 获取广告主名称选项
   */
  const fetchCorporationOptions = async () => {
    corporationLoading.value = true
    try {
        const params = {
            page: corporationCurrentPage.value,
            limit: corporationPageSize.value,
            ad_account_id: corporationKeyword.value,
        }
        
        const response = await getCorporationList(params)
        console.log(response,'responseresponseresponse')
        if (response.lists) {
            corporationOptions.value = response.lists || []
            corporationTotal.value = response.count || 0
        } else {
            ElMessage.error(response.msg || '获取广告主列表失败')
            corporationOptions.value = []
            corporationTotal.value = 0
        }
    } catch (error) {
        console.error('获取广告主列表出错:', error)
        ElMessage.error('获取广告主列表失败')
        corporationOptions.value = []
        corporationTotal.value = 0
    } finally {
        corporationLoading.value = false
    }
}

  /**
   * 远程搜索广告主名称
   * @param {string} query - 搜索关键词
   */
  const remoteSearchCorporation = (query: string) => {
    corporationKeyword.value = query
    corporationCurrentPage.value = 1
    fetchCorporationOptions()
  }

  /**
   * 处理广告主名称分页变化
   * @param {number} page - 页码
   */
  const handleCorporationPageChange = (page: number) => {
    corporationCurrentPage.value = page
    fetchCorporationOptions()
  }

  // 监听对话框关闭
  watch(dialogVisible, (newVal) => {
      if (!newVal) {
          // 对话框关闭时清理数据，但不触发接口调用
          cleanupFormData()
      }
  })
  
  // 清理表单数据，避免触发接口调用
  const cleanupFormData = () => {
      if (!formRef.value) return
      
      // 设置清理标志，暂时禁用监听器
      isCleaning.value = true
      
      // 重置表单字段
      formRef.value.resetFields()
      
      // 重置表单数据，但不触发监听器
      Object.assign(formData, {
          id: '',
          ad_account_id: '',
          account_id: '',
          corporation_name: '',
          ad_group_id: '',
          positionType: 'auto',
          gender: 'ALL',
          person_type: ['LIVE_IN'],
          marketing_goal: 'MARKETING_GOAL_LEAD_RETENTION',
          target_asset_id: '',
          optimization_goal: '',
          marketing_target_type: '',
          custom_audience: [],
          excluded_custom_audience: [],
          ad_group_name: '',
          description: '',
          position: [],
          region: [],
          age: [],
          bid_type: BidType.OCPM,
          bid_amount: 0,
          daily_budget: 0,
          startTime: undefined,
          endTime: undefined,
          timeRange: undefined
      })
      
      // 重置其他状态
      regionType.value = 'all'
      ageType.value = 'all'
      customAudienceType.value = 'all'
      // 清空选项数据
      marketingTargetTypes.value = {}
      targetAssetOptions.value = []
      optimizationGoals.value = []
      customAudienceOptions.value = []
      
      // 清理定时器
      if (marketingGoalChangeTimer.value) {
          clearTimeout(marketingGoalChangeTimer.value)
          marketingGoalChangeTimer.value = null
      }
      if (targetAssetSearchTimer.value) {
          clearTimeout(targetAssetSearchTimer.value)
          targetAssetSearchTimer.value = null
      }
      if (regionSearchTimer.value) {
          clearTimeout(regionSearchTimer.value)
          regionSearchTimer.value = null
      }
      
      // 重置加载状态
      marketingTargetTypeLoading.value = false
      targetAssetLoading.value = false
      optimizationGoalLoading.value = false
      
      // 延迟重置清理标志
      nextTick(() => {
          isCleaning.value = false
      })
      
      console.log('表单数据已清理，未触发接口调用')
  }
  
  // 新建广告
  const handleAdd = () => {
      dialogType.value = 'add'
      dialogVisible.value = true
      // 使用新的清理函数，避免触发接口调用
      cleanupFormData()
  }
  
  // 编辑广告
  const handleEdit = async (row: AdListItem) => {
      // 权限检查
      if (!hasAdvertiserPermission(row)) {
          ElMessage.warning(getPermissionMessage(row))
          return
      }
      
      try {
          dialogType.value = 'edit'
          currentAdId.value = row.id
          const data = await getAdDetail(row.id)
          console.log(data,'datadata')
          
          // 基础字段映射
          formData.ad_group_name = data.ad_group_name || data.adgroup_name || ''
          formData.ad_group_id = data.ad_group_id || data.adgroup_id || ''
          formData.marketing_goal = data.marketing_goal || 'MARKETING_GOAL_LEAD_RETENTION'
          formData.marketing_target_type = data.marketing_target_type || ''
          formData.target_asset_id = data.marketing_asset_id ? String(data.marketing_asset_id) : ''
          formData.optimization_goal = data.optimization_goal || ''
          formData.bid_type = data.bid_mode === 'BID_MODE_OCPM' ? BidType.OCPM : BidType.OCPM
          formData.bid_amount = data.bid_amount ? data.bid_amount / 100 : 0 // 转换为元
          formData.daily_budget = data.daily_budget ? data.daily_budget / 100 : 0 // 转换为元
          
          // 调试信息
          console.log('编辑时设置的基础字段:')
          console.log('marketing_asset_id:', data.marketing_asset_id)
          console.log('target_asset_id:', formData.target_asset_id)
          console.log('marketing_target_type:', formData.marketing_target_type)
          
          // 时间字段处理
          if (data.begin_date) {
              formData.startTime = new Date(data.begin_date)
          }
          if (data.end_date) {
              formData.endTime = new Date(data.end_date)
          }
          
          // 广告主账号信息处理 - 优先使用接口返回的数据
          formData.ad_account_id = data.ad_account_id || row.ad_account_id || ''
          formData.account_id = data.account_id || row.account_id || ''
          formData.corporation_name = row.corporation_name || ''
          
          // 设置广告主账号选择器的值 - 需要根据id匹配
          // 先尝试从当前账号选项中查找匹配的账号
          const matchedAccount = accountOptions.value.find(account => 
              account.ad_account_id === formData.ad_account_id && 
              account.account_id === formData.account_id
          )
          
          if (matchedAccount) {
              formData.id = String(matchedAccount.id)
          } else {
              // 如果没有找到匹配的账号，需要重新加载账号列表并查找
              formData.id = ''
              // 这里会在handleEditDataLoad中处理
          }
          
          // 处理年龄定向
          if (data.targeting && data.targeting.age && Array.isArray(data.targeting.age)) {
              const ageRanges = data.targeting.age
              formData.age = ageRanges.map((range: { min: number; max: number }) => {
                  const min = range.min
                  const max = range.max
                  // 根据年龄范围匹配到对应的选项值
                  if (min === 14 && max === 18) return '14-18'
                  if (min === 19 && max === 24) return '19-24'
                  if (min === 25 && max === 29) return '25-29'
                  if (min === 30 && max === 39) return '30-39'
                  if (min === 40 && max === 49) return '40-49'
                  if (min === 50 && max === 66) return '50-66'
                  return ''
              }).filter((age: string) => age !== '')
              
              // 设置年龄类型
              if (formData.age.length > 0) {
                  ageType.value = 'custom'
              } else {
                  ageType.value = 'all'
              }
          } else {
              formData.age = []
              ageType.value = 'all'
          }
          
          // 处理性别定向（需要根据实际返回数据调整）
          formData.gender = data.gender || 'ALL' // 默认值，需要根据实际数据调整
          
          // 处理地域定向
          if (data.targeting && data.targeting.geo_location) {
              const geoLocation = data.targeting.geo_location
              
              // 设置location_types
              if (geoLocation.location_types && Array.isArray(geoLocation.location_types)) {
                  formData.person_type = geoLocation.location_types
              } else {
                  formData.person_type = ['LIVE_IN']
              }
              
              // 处理regions
              if (geoLocation.regions && Array.isArray(geoLocation.regions) && geoLocation.regions.length > 0) {
                  regionType.value = 'region'
                  formData.region = geoLocation.regions.map(String)
                  
                  // 需要加载地域选项并匹配选中的区域
                  await handleGeoLocationRegions(geoLocation.regions)
              } else {
                  regionType.value = 'all'
                  selectedProvince.value = []
                  selectedCity.value = []
                  selectedDistrict.value = []
                  formData.region = []
                  formData.person_type = ['LIVE_IN']
              }
          } else {
              // 默认处理
              regionType.value = 'all'
              selectedProvince.value = []
              selectedCity.value = []
              selectedDistrict.value = []
              formData.region = []
              formData.person_type = ['LIVE_IN']
          }
          
          // 处理广告版位
          if (data.automatic_site_enabled) {
              formData.positionType = 'auto'
          } else {
              formData.positionType = 'specific'
              // 根据site_set设置具体版位
              formData.position = data.site_set || []
          }
          
          // 处理自定义人群
          if (data.targeting && data.targeting.custom_audience && Array.isArray(data.targeting.custom_audience) && data.targeting.custom_audience.length > 0) {
              customAudienceType.value = 'target'
              formData.custom_audience = data.targeting.custom_audience.map(String)
              console.log('编辑时设置定向人群:', formData.custom_audience)
          } else if (data.targeting && data.targeting.excluded_custom_audience && Array.isArray(data.targeting.excluded_custom_audience) && data.targeting.excluded_custom_audience.length > 0) {
              customAudienceType.value = 'exclude'
              formData.excluded_custom_audience = data.targeting.excluded_custom_audience.map(String)
              console.log('编辑时设置非定向人群:', formData.excluded_custom_audience)
          } else {
              customAudienceType.value = 'all'
              formData.custom_audience = []
              formData.excluded_custom_audience = []
              console.log('编辑时设置自定义人群为不限')
          }
          
          // 设置其他默认值
          formData.person_type = ['LIVE_IN']
          formData.description = ''
          formData.timeRange = undefined
          
          // 打开对话框
          dialogVisible.value = true
          // 调用相关接口获取选项数据
          await handleEditDataLoad()
          
      } catch (error) {
          console.error('获取广告详情失败：', error)
          ElMessage.error('获取广告详情失败')
      }
  }
  
  // 编辑时加载相关数据
  const handleEditDataLoad = async () => {
      try {
          // 设置编辑加载标志，防止监听器触发
          isEditingLoading.value = true
          
          // 如果有广告主账号信息，加载相关选项
          if (formData.ad_account_id && formData.account_id) {
              // 先加载账号列表，确保能找到对应的账号
              const accountFound = await loadAccountForEdit()
              console.log(accountFound,'accountFoundaccountFoundaccountFound')
              // 如果找到了账号，才继续执行后续的接口调用
              if (accountFound) {
                  // 第一步：加载营销目的类型
                  await fetchMarketingTargetTypes()
                  
                  // 第二步：等待营销目的类型加载完成后，加载产品列表
                  await nextTick()
                  if (formData.marketing_target_type) {
                      await remoteSearchTargetAsset()
                      // 等待产品列表加载完成后，匹配marketing_asset_id
                      await nextTick()
                      await matchMarketingAssetId()
                      // 注意：优化目标现在会在产品匹配成功后自动加载，不需要在这里重复调用
                  }

                  // 第三步：根据自定义人群数据设置类型和加载选项
                  if (formData.custom_audience && formData.custom_audience.length > 0) {
                      // 如果有定向人群数据，设置为定向人群类型
                      customAudienceType.value = 'target'
                      await fetchCustomAudienceOptions()
                  } else if (formData.excluded_custom_audience && formData.excluded_custom_audience.length > 0) {
                      // 如果有非定向人群数据，设置为非定向人群类型
                      customAudienceType.value = 'exclude'
                      await fetchCustomAudienceOptions()
                  } else {
                      // 如果都没有，设置为不限
                      customAudienceType.value = 'all'
                  }
              }
          }
          
          // 注意：地域选项已经在handleEdit中的handleGeoLocationRegions函数中处理了
          
      } catch (error) {
          console.error('加载编辑数据失败：', error)
      } finally {
          // 重置编辑加载标志
          isEditingLoading.value = false
      }
  }
  
  // 匹配marketing_asset_id到产品列表
  const matchMarketingAssetId = async () => {
      if (!formData.target_asset_id || !targetAssetOptions.value.length) {
          return
      }
      
      try {
          console.log('开始匹配marketing_asset_id:', formData.target_asset_id)
          console.log('可用的产品列表:', targetAssetOptions.value)
          
          // 在产品列表中查找匹配的marketing_asset_id
          const matchedAsset = targetAssetOptions.value.find(
              (asset: TargetAssetOption) => {
                  // 确保比较时类型一致（都转换为字符串）
                  const assetId = String(asset.marketing_asset_id)
                  const targetId = String(formData.target_asset_id)
                  return assetId === targetId
              }
          )
          
          if (matchedAsset) {
              console.log('找到匹配的产品:', matchedAsset)
              // 确保target_asset_id是字符串格式
              formData.target_asset_id = String(matchedAsset.marketing_asset_id)
              
              // 产品匹配成功后，手动触发优化目标加载
              console.log('产品匹配成功，手动触发优化目标加载')
              await fetchOptimizationGoals()
          } else {
              console.warn('未找到匹配的产品，marketing_asset_id:', formData.target_asset_id)
              console.log('可用的产品列表:', targetAssetOptions.value)
              
              // 如果没有找到匹配的产品，尝试重新加载产品列表
              console.log('尝试重新加载产品列表...')
              await remoteSearchTargetAsset()
              await nextTick()
              
              // 再次尝试匹配
              const retryMatchedAsset = targetAssetOptions.value.find(
                  (asset: TargetAssetOption) => {
                      const assetId = String(asset.marketing_asset_id)
                      const targetId = String(formData.target_asset_id)
                      return assetId === targetId
                  }
              )
              
              if (retryMatchedAsset) {
                  console.log('重试后找到匹配的产品:', retryMatchedAsset)
                  formData.target_asset_id = String(retryMatchedAsset.marketing_asset_id)
                  
                  // 重试匹配成功后，手动触发优化目标加载
                  console.log('重试产品匹配成功，手动触发优化目标加载')
                  await fetchOptimizationGoals()
              } else {
                  console.error('重试后仍未找到匹配的产品')
                  ElMessage.warning(`未找到匹配的产品，产品ID: ${formData.target_asset_id}`)
                  formData.target_asset_id = ''
              }
          }
      } catch (error) {
          console.error('匹配marketing_asset_id失败:', error)
      }
  }
  
  // 为编辑加载账号信息
  const loadAccountForEdit = async (): Promise<boolean> => {
      try {
          // 使用广告主ID搜索账号
          const params = {
              "account_role_type": "ACCOUNT_ROLE_TYPE_ADVERTISER",
              page_no: 1,
              page_size: 50, // 增加页面大小以找到目标账号
              ad_account_id: formData.ad_account_id, // 使用广告主ID搜索
              corporation_name: formData.corporation_name // 使用公司名称过滤
          }
          
          const res = await apiGetAccounts(params)
          if (res.list && res.list.length > 0) {
              // 更新账号选项
              accountOptions.value = res.list
              accountTotal.value = res.total || 0
              
              // 查找匹配的账号
              const matchedAccount = res.list.find((account: AccountOption) => 
                  account.ad_account_id === formData.ad_account_id && 
                  account.account_id === formData.account_id
              )
              
              if (matchedAccount) {
                  formData.id = String(matchedAccount.id)
                  formData.corporation_name = matchedAccount.corporation_name
                  return true
              } else {
                  console.warn('未找到匹配的账号信息')
                  ElMessage.warning('未找到匹配的账号信息，请手动选择')
                  return false
              }
          } else {
              console.warn('未找到账号信息')
              ElMessage.warning('未找到账号信息，确认账号是否为代理商，请手动选择')
              return false
          }
      } catch (error) {
          console.error('加载账号信息失败：', error)
          ElMessage.error('加载账号信息失败')
          return false
      }
  }
  
  // 处理编辑时的地域数据匹配
  const handleGeoLocationRegions = async (regionIds: number[]) => {
      try {
          console.log('开始处理地域数据匹配，regionIds:', regionIds)
          
          // 先加载省份数据
          await fetchProvinceOptions()
          
          // 查找匹配的省份
          const matchedProvinces = provinceOptions.value.filter(province => 
              regionIds.includes(Number(province.id))
          )
          
          if (matchedProvinces.length > 0) {
              selectedProvince.value = matchedProvinces.map(p => p.id)
              console.log('找到匹配的省份:', selectedProvince.value)
              
              // 加载城市数据
              await fetchCityOptions(selectedProvince.value)
              
              // 查找匹配的城市
              const matchedCities = cityOptions.value.filter(city => 
                  regionIds.includes(Number(city.id))
              )
              
              if (matchedCities.length > 0) {
                  selectedCity.value = matchedCities.map(c => c.id)
                  console.log('找到匹配的城市:', selectedCity.value)
                  
                  // 加载区县数据
                  await fetchDistrictOptions(selectedCity.value)
                  
                  // 查找匹配的区县
                  const matchedDistricts = districtOptions.value.filter(district => 
                      regionIds.includes(Number(district.id))
                  )
                  
                  if (matchedDistricts.length > 0) {
                      selectedDistrict.value = matchedDistricts.map(d => d.id)
                      console.log('找到匹配的区县:', selectedDistrict.value)
                  }
              }
          }
          
          // 更新选中的区域
          updateSelectedRegions()
          
      } catch (error) {
          console.error('处理地域数据匹配失败：', error)
          ElMessage.warning('地域数据匹配失败，请手动选择')
      }
  }
  
  // 查看广告
  const handleView = async (row: AdListItem) => {
      try {
          const { data } = await getAdDetail(row.id)
          // TODO: 实现查看逻辑
          console.log('广告详情：', data)
      } catch (error) {
          console.error('获取广告详情失败：', error)
          ElMessage.error('获取广告详情失败')
      }
  }
  
  // 删除广告
  const handleDelete = async (row: AdListItem) => {
      try {
          await ElMessageBox.confirm('注意：删除后无法恢复，确定要删除该广告吗？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
          })
          await deleteAd({
              account_id: row.account_id,
              ad_group_id: row.ad_group_id
          })
          ElMessage.success('删除成功')
          getLists()
      } catch (error) {
          if (error !== 'cancel') {
              console.error('删除广告失败：', error)
              ElMessage.error('删除广告失败')
          }
      }
  }
  
  // 表单引用
  const formRef = ref()
  
  // 表单验证规则
  const rules: Record<string, FormItemRule[]> = {
    ad_group_name: [
      { required: true, message: '请输入广告名称', trigger: 'blur' }
    ],
    id: [
      { required: true, message: '请选择广告主账号', trigger: 'change' }
    ],
    target_asset_id: [
      { required: true, message: '请选择教育产品', trigger: 'change' }
    ],
    bid_type: [
      { required: true, message: '请选择出价方式', trigger: 'change' }
    ],
    bid_amount: [
      { required: true, message: '请输入出价金额', trigger: 'blur' },
      { type: 'number' as const, min: 0.01, message: '出价金额必须大于1分', trigger: 'blur' }
    ],
    startTime: [
      { required: true, message: '请选择开始时间', trigger: 'change' }
    ],
    endTime: [
      { required: true, message: '请选择结束时间', trigger: 'change' }
    ],
    optimization_goal: [
      { required: true, message: '请选择优化目标', trigger: 'change' }
    ]
  }
  
  // 自定义验证函数：检查是否同时选择了三个不限
  const validateTargeting = () => {
    // if (regionType.value === 'all' && ageType.value === 'all' && formData.gender === 'ALL') {
    //   return false
    // }
    return true
  }
  
  // 提交表单
  const submitLoading = ref(false)
  
  // 添加创意跳转弹框相关变量
  const creativeJumpDialogVisible = ref(false)
  const currentCreatedAd = ref<any>(null)
  
  // 创意选择相关变量
  const creativeSelectDialogVisible = ref(false)
  const creativeListLoading = ref(false)
  const creativeList = ref<any[]>([])
  const currentAdForCreative = ref<any>(null)
  const selectedCreative = ref<any>(null)
  const creativeJumpLoading = ref(false)
  
  const handleSubmit = async () => {
    if (!formRef.value) return
    submitLoading.value = true
    const loadingInstance = ElLoading.service({
      lock: true,
      text: '提交中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    try {
      await formRef.value.validate(async (valid: boolean) => {
        if (valid) {
          // 验证定向设置
          if (!validateTargeting()) {
            ElMessage.error('地域、年龄、性别不能同时选择不限')
            return
          }
  
          const submitData = {
            ...formData,
            optimization_goal: formData.optimization_goal,
            region_type: regionType.value,
            custom_audience_type: customAudienceType.value
          }
          
          if (dialogType.value === 'add') {
            const result = await createAd(submitData)
            ElMessage.success('创建成功')
            // 保存当前创建的广告信息，用于跳转到创意页面
            currentCreatedAd.value = {
              ad_group_id: result?.ad_group_id || formData.ad_group_id,
              ad_group_name: formData.ad_group_name,
              account_id: formData.account_id,
              ad_account_id: formData.ad_account_id,
              corporation_name: formData.corporation_name
            }
            // 显示创意跳转弹框
            creativeJumpDialogVisible.value = true
          } else {
            await updateAd(currentAdId.value, submitData)
            ElMessage.success('更新成功')
          }
          dialogVisible.value = false
          getLists()
        }
      })
    } catch (error: any) {
      if (error.response?.data?.message) {
        ElMessage.error({
          message: error.response.data.message,
          duration: 15000
        })
      } else {
        ElMessage.error('表单验证失败，请检查必填项')
      }
      console.error('保存广告失败：', error)
    } finally {
      submitLoading.value = false
      loadingInstance.close()
    }
  }
  
  // 复制到剪贴板
  const copyToClipboard = (text: string) => {
      navigator.clipboard.writeText(text).then(() => {
          ElMessage.success('复制成功')
      }).catch(() => {
          ElMessage.error('复制失败')
      })
  }
  
  // 监听推广产品类型变化
  watch(() => formData.marketing_target_type, (newVal) => {
    if (newVal && formData.ad_account_id && !isCleaning.value) {
      // 只在新建时清空已选择的产品，编辑时保持选择
      if (dialogType.value === 'add') {
        formData.target_asset_id = ''
      }
      
      // 重置加载状态
      targetAssetLoading.value = false
      
      // 使用防抖，避免频繁请求
      if (targetAssetSearchTimer.value) {
        clearTimeout(targetAssetSearchTimer.value)
      }
      
      targetAssetSearchTimer.value = setTimeout(() => {
        console.log('营销目标类型变化，开始获取产品列表')
        remoteSearchTargetAsset()
      }, 300) // 300ms防抖
    } else {
      targetAssetOptions.value = []
      // 只在新建时清空产品选择
      if (dialogType.value === 'add') {
        formData.target_asset_id = ''
        // 只在新建时清空优化目标
        formData.optimization_goal = ''
        optimizationGoals.value = []
      }
    }
  })
  
  // 监听广告主账号变化
  watch(() => formData.ad_account_id, (newVal) => {
    // 在编辑加载时跳过执行，避免与handleEditDataLoad冲突
    if (isEditingLoading.value) {
      return
    }
    
    if (newVal && !isCleaning.value) {
      // 只在新建时清空相关选项，编辑时保持选择
      if (dialogType.value === 'add') {
        formData.target_asset_id = ''
        formData.marketing_target_type = ''
        marketingTargetTypes.value = {}
        targetAssetOptions.value = []
      }
      // 获取推广产品类型
      fetchMarketingTargetTypes()
    } else {
      targetAssetOptions.value = []
      // 只在新建时清空相关选项
      if (dialogType.value === 'add') {
        formData.target_asset_id = ''
        marketingTargetTypes.value = {}
        formData.marketing_target_type = ''
      }
    }
  })
  
  // 监听推广产品类型选项变化，有数据时默认选中第一个
  watch(marketingTargetTypes, (newVal) => {
    if (newVal && Object.keys(newVal).length > 0) {
      // 只在新建时默认选中第一个，编辑时保持原有选择
      if (dialogType.value === 'add' && !formData.marketing_target_type) {
        formData.marketing_target_type = Object.keys(newVal)[0]
      }
    }
  })
  
  // 获取产品列表
  const remoteSearchTargetAsset = async (query: string = '') => {
    if (!formData.ad_account_id || !formData.marketing_target_type) {
      return
    }
    
    // 如果正在加载，先取消之前的请求
    if (targetAssetLoading.value) {
      console.log('取消之前的产品列表请求')
      return
    }
    
    targetAssetLoading.value = true
    try {
      const res = await get_target_assets({ 
        ad_account_id: formData.ad_account_id,
        account_id: formData.account_id,
        marketing_target_type: formData.marketing_target_type,
        keyword: query 
      })
      targetAssetOptions.value = res || []
      
      // 编辑时：检查当前选择的产品是否在新的选项中
      if (dialogType.value === 'edit' && formData.target_asset_id) {
        const targetAssetExists = targetAssetOptions.value.some(
          (asset: TargetAssetOption) => {
            // 确保比较时类型一致（都转换为字符串）
            const assetId = String(asset.marketing_asset_id)
            const targetId = String(formData.target_asset_id)
            return assetId === targetId
          }
        )
        if (!targetAssetExists) {
          console.warn('当前选择的产品不在可用选项中，已清空选择')
          console.log('当前选择的产品ID:', formData.target_asset_id)
          console.log('可用的产品列表:', targetAssetOptions.value)
          formData.target_asset_id = ''
          // 编辑时不清空优化目标，等待用户重新选择产品后再更新
          console.log('编辑模式下，保持优化目标选择，等待用户重新选择产品')
        } else {
          console.log('找到匹配的产品，产品ID:', formData.target_asset_id)
          // 匹配成功后，加载优化目标
          nextTick(() => {
            console.log('产品匹配成功，开始加载优化目标')
            fetchOptimizationGoals()  // 取消注释，确保产品匹配成功后加载优化目标
          })
        }
      }
    } catch (error: any) {
      // 如果是取消请求的错误，不显示错误信息
      if (error.name === 'CanceledError' || error.code === 'ERR_CANCELED') {
        console.log('产品列表请求已取消')
        return
      }
      
      console.error('获取产品列表失败：', error)
      ElMessage.error('获取产品列表失败')
      targetAssetOptions.value = []
      // 编辑时如果获取失败，清空产品选择
      if (dialogType.value === 'edit') {
        formData.target_asset_id = ''
        // 编辑时不清空优化目标，等待用户重新选择产品后再更新
        console.log('编辑模式下，获取产品列表失败，保持优化目标选择')
      }
    } finally {
      targetAssetLoading.value = false
    }
  }
  
  // 监听省份变化
  watch(selectedProvince, async (newVal) => {
      if (newVal.length > 0) {
          // 使用防抖，避免频繁请求
          if (regionSearchTimer.value) {
              clearTimeout(regionSearchTimer.value)
          }
          regionSearchTimer.value = setTimeout(async () => {
              await fetchCityOptions(newVal)
          }, 300) // 300ms防抖
      } else {
          cityOptions.value = []
          districtOptions.value = []
          selectedCity.value = []
          selectedDistrict.value = []
      }
  })
  
  // 监听城市变化
  watch(selectedCity, async (newVal) => {
      if (newVal.length > 0) {
          // 使用防抖，避免频繁请求
          if (regionSearchTimer.value) {
              clearTimeout(regionSearchTimer.value)
          }
          regionSearchTimer.value = setTimeout(async () => {
              await fetchDistrictOptions(newVal)
          }, 300) // 300ms防抖
      } else {
          districtOptions.value = []
          selectedDistrict.value = []
      }
  })
  
  // 获取省份列表
  const fetchProvinceOptions = async () => {
      // 如果正在加载，先取消之前的请求
      if (regionLoading.value) {
          console.log('取消之前的省份列表请求')
          return
      }
      
      regionLoading.value = true
      try {
          const res = await get_targeting_tags({ type: 'province' })
          provinceOptions.value = res || []
      } catch (error: any) {
          // 如果是取消请求的错误，不显示错误信息
          if (error.name === 'CanceledError' || error.code === 'ERR_CANCELED') {
              console.log('省份列表请求已取消')
              return
          }
          console.error('获取省份列表失败：', error)
          ElMessage.error('获取省份列表失败')
          provinceOptions.value = []
      } finally {
          regionLoading.value = false
      }
  }
  
  // 获取城市列表
  const fetchCityOptions = async (provinceIds: string[]) => {
      // 如果正在加载，先取消之前的请求
      if (regionLoading.value) {
          console.log('取消之前的城市列表请求')
          return
      }
      
      regionLoading.value = true
      try {
          const res = await get_targeting_tags({ 
              type: 'city',
              province_ids: provinceIds
          })
          cityOptions.value = res || []
      } catch (error: any) {
          // 如果是取消请求的错误，不显示错误信息
          if (error.name === 'CanceledError' || error.code === 'ERR_CANCELED') {
              console.log('城市列表请求已取消')
              return
          }
          console.error('获取城市列表失败：', error)
          ElMessage.error('获取城市列表失败')
          cityOptions.value = []
      } finally {
          regionLoading.value = false
      }
  }
  
  
  
  
  // 获取区县列表
  const fetchDistrictOptions = async (cityIds: string[]) => {
      // 如果正在加载，先取消之前的请求
      if (regionLoading.value) {
          console.log('取消之前的区县列表请求')
          return
      }
      
      regionLoading.value = true
      try {
          const res = await get_targeting_tags({ 
              type: 'district',
              city_ids: cityIds
          })
          districtOptions.value = res || []  
      } catch (error: any) {
          // 如果是取消请求的错误，不显示错误信息
          if (error.name === 'CanceledError' || error.code === 'ERR_CANCELED') {
              console.log('区县列表请求已取消')
              return
          }
          console.error('获取区县列表失败：', error)
          ElMessage.error('获取区县列表失败')
          districtOptions.value = []
      } finally {
          regionLoading.value = false
      }
  }
  
  // 监听区域类型变化
  watch(regionType, (newVal) => {
      if (newVal === 'all') {
          selectedProvince.value = []
          selectedCity.value = []
          selectedDistrict.value = []
          formData.region = []
      } else {
          fetchProvinceOptions()
      }
  })
  
  // 更新选中的区域
  const updateSelectedRegions = () => {
      const regions = []
      if (selectedProvince.value.length > 0) {
          regions.push(...selectedProvince.value)
      }
      if (selectedCity.value.length > 0) {
          regions.push(...selectedCity.value)
      }
      if (selectedDistrict.value.length > 0) {
          regions.push(...selectedDistrict.value)
      }
      formData.region = regions
  }
  
  // 监听选中值变化
  watch([selectedProvince, selectedCity, selectedDistrict], () => {
      updateSelectedRegions()
  })
  
  // 初始化
  onMounted(() => {
      getLists()
      // fetchMarketingTargetTypes()
  })
  
  // 在 script setup 部分添加
  const ageType = ref('all')
  
  // 监听年龄类型变化
  watch(ageType, (newVal) => {
    if (newVal === 'all') {
      formData.age = []
    }
  })
  
  type MarketingGoal = 'MARKETING_GOAL_LEAD_RETENTION' | 'MARKETING_GOAL_BRAND_PROMOTION';
  
  const marketingGoals = [
    { value: 'MARKETING_GOAL_LEAD_RETENTION' as MarketingGoal, label: '线索留资', icon: 'ShoppingBag' },
    { value: 'MARKETING_GOAL_BRAND_PROMOTION' as MarketingGoal, label: '品牌宣传', icon: 'Promotion' }
  ] as const;
  
  // 优化目标选项
  interface OptimizationGoal {
    value: string;
    label: string;
  }
  
  // 优化目标字典
  const optimizationGoalDict = {
    'OPTIMIZATIONGOAL_ONLINE_CONSULTATION': '在线咨询',
    'OPTIMIZATIONGOAL_PAGE_RESERVATION': '表单预约',
    'OPTIMIZATIONGOAL_CLICK': '点击',
    'OPTIMIZATIONGOAL_CANVAS_CLICK': '跳转按钮点击',
    'OPTIMIZATIONGOAL_PROMOTION_VIEW_KEY_PAGE': '关键页面访问次数'
  } as const
  
  const optimizationGoals = ref<OptimizationGoal[]>([])
  const optimizationGoalLoading = ref(false)
  
  // 防抖定时器
  const marketingGoalChangeTimer = ref<number | null>(null)
  const targetAssetSearchTimer = ref<number | null>(null)
  const regionSearchTimer = ref<number | null>(null)
  
  // 清理标志，用于避免清理时触发监听器
  const isCleaning = ref(false)
  
  // 编辑时加载标志，用于防止监听器触发
  const isEditingLoading = ref(false)
  
  // 获取优化目标权限
  const fetchOptimizationGoals = async () => {
    if (!formData.ad_account_id || !formData.marketing_goal || !formData.marketing_target_type) {
      console.log('获取优化目标的条件不满足:', {
        ad_account_id: formData.ad_account_id,
        marketing_goal: formData.marketing_goal,
        marketing_target_type: formData.marketing_target_type
      })
      optimizationGoals.value = []
      // 只在新建时清空优化目标
      if (dialogType.value === 'add') {
        formData.optimization_goal = ''
      }
      return
    }
    
    // 如果正在加载，先取消之前的请求
    if (optimizationGoalLoading.value) {
      console.log('取消之前的优化目标请求')
      return
    }
    
    console.log('开始获取优化目标，参数:', {
      ad_account_id: formData.ad_account_id,
      account_id: formData.account_id,
      marketing_goal: formData.marketing_goal,
      marketing_target_type: formData.marketing_target_type
    })
    
    optimizationGoalLoading.value = true
    try {
      const res = await get_optimization_goal_permissions({
        ad_account_id: formData.ad_account_id,
        account_id: formData.account_id,
        marketing_goal: formData.marketing_goal,
        marketing_target_type: formData.marketing_target_type
      })
      console.log('获取优化目标结果:', res)
      if (res && Array.isArray(res)) {
        optimizationGoals.value = res.map(value => ({
          value,
          label: optimizationGoalDict[value as keyof typeof optimizationGoalDict] || value
        }))
        
        // 编辑时：检查当前选择的优化目标是否在新的选项中
        if (dialogType.value === 'edit') {
          if (formData.optimization_goal && !res.includes(formData.optimization_goal)) {
            console.warn('当前选择的优化目标不在可用选项中，已清空选择')
            formData.optimization_goal = ''
          }
        } else {
          // 新建时：如果当前选中的值不在新的选项中，清空选择
          if (formData.optimization_goal && !res.includes(formData.optimization_goal)) {
            formData.optimization_goal = ''
          }
        }
        
        console.log('优化目标已更新:', optimizationGoals.value)
      } else {
        optimizationGoals.value = []
        // 只在新建时清空优化目标
        if (dialogType.value === 'add') {
          formData.optimization_goal = ''
        }
      }
    } catch (error: any) {
      // 如果是取消请求的错误，不显示错误信息
      if (error.name === 'CanceledError' || error.code === 'ERR_CANCELED') {
        console.log('优化目标请求已取消')
        return
      }
      
      console.error('获取优化目标失败：', error)
      ElMessage.error({
        message: error.response?.data?.message || '获取优化目标失败',
        duration: 15000
      })
      optimizationGoals.value = []
      // 只在新建时清空优化目标
      if (dialogType.value === 'add') {
        formData.optimization_goal = ''
      }
    } finally {
      optimizationGoalLoading.value = false
    }
  }
  
  // 监听依赖项变化
  watch([
  //  () => formData.ad_account_id,
    () => formData.marketing_goal,
    () => formData.marketing_target_type,
    () => formData.target_asset_id  // 添加对产品选择的监听
  ], () => {
    // 在新建和编辑时都自动获取优化目标，但清理时不调用
    if (formData.ad_account_id && formData.marketing_goal && formData.marketing_target_type && !isCleaning.value) {
      // 编辑时：只有在选择了产品后才重新加载优化目标
      if (dialogType.value === 'edit' && !formData.target_asset_id) {
        console.log('编辑模式下，未选择产品，跳过优化目标加载')
        return
      }
      
      console.log('依赖项变化，开始获取优化目标')
      fetchOptimizationGoals()
    }
  })
  
  // 年龄选项
  const ageOptions = [
    { label: '14-18岁', value: '14-18' },
    { label: '19-24岁', value: '19-24' },
    { label: '25-29岁', value: '25-29' },
    { label: '30-39岁', value: '30-39' },
    { label: '40-49岁', value: '40-49' },
    { label: '50岁及以上', value: '50-66' }
  ]
  
  // 监听广告主账号选择变化
  const handleAccountChange = (val: string) => {
    // 在编辑加载时跳过执行，避免与handleEditDataLoad冲突
    if (isEditingLoading.value) {
      return
    }
    
    const selected = accountOptions.value.find(item => String(item.id) === val)
    if (selected) {
      formData.id = String(selected.id)
      formData.ad_account_id = selected.ad_account_id
      formData.account_id = selected.account_id
      formData.corporation_name = selected.corporation_name
      
      // 只在新建时清空依赖的选项，编辑时保持选择
      if (dialogType.value === 'add') {
        formData.target_asset_id = ''
        formData.marketing_target_type = ''
        formData.optimization_goal = ''
        marketingTargetTypes.value = {}
        targetAssetOptions.value = []
        optimizationGoals.value = []
        
        // 清空自定义人群相关数据
        formData.custom_audience = []
        formData.excluded_custom_audience = []
        customAudienceType.value = 'all'
        customAudienceOptions.value = []
      }
      
      // 重置加载状态
      marketingTargetTypeLoading.value = false
      
      // 使用防抖，避免频繁请求
      if (marketingGoalChangeTimer.value) {
        clearTimeout(marketingGoalChangeTimer.value)
      }
      
      marketingGoalChangeTimer.value = setTimeout(() => {
        console.log('账号变化，开始调用fetchMarketingTargetTypes')
        fetchMarketingTargetTypes()
      }, 300) // 300ms防抖
    } else {
      formData.id = ''
      formData.ad_account_id = ''
      formData.account_id = ''
      formData.corporation_name = ''
      formData.target_asset_id = ''
      formData.marketing_target_type = ''
      formData.optimization_goal = ''
      marketingTargetTypes.value = {}
      targetAssetOptions.value = []
      optimizationGoals.value = []
      
      // 清空自定义人群相关数据
      formData.custom_audience = []
      formData.excluded_custom_audience = []
      customAudienceType.value = 'all'
      customAudienceOptions.value = []
    }
  }
  
  // 复制相关
  const copyDialogVisible = ref(false)
  const copyLoading = ref(false)
  const currentCopyRow = ref<AdListItem | null>(null)
  const copyForm = reactive({
    ad_group_name: '',
    selectedIds: [] as string[],
    startTime: undefined as Date | undefined,
    endTime: undefined as Date | undefined
  })

  // 数据分析相关
  const dataAnalysisDialogVisible = ref(false)
  const dataAnalysisLoading = ref(false)
  const dataAnalysisData = ref<any>(null)
  const currentAnalysisRow = ref<AdListItem | null>(null)
  
  // 监听复制选择变化
  watch(() => copyForm.selectedIds, () => {
    updateCopySelectStatus()
  }, { deep: true })
  
  // 复制弹框的账号相关
  const copyAccountOptions = ref<AccountOption[]>([])
  const copyAccountLoading = ref(false)
  const copyAccountTotal = ref(0)
  const copyAccountCurrentPage = ref(1)
  const copyAccountPageSize = ref(10)
  const copyAccountKeyword = ref('')
  
  // 复制全选相关
  const copySelectAll = ref(false)
  const copySelectIndeterminate = ref(false)
  
  // 处理复制全选
  const handleCopySelectAll = (val: CheckboxValueType) => {
    const isChecked = Boolean(val)
    if (isChecked) {
      // 全选当前页面的所有选项
      const currentPageIds = copyAccountOptions.value.map(item => String(item.id))
      copyForm.selectedIds = [...new Set([...copyForm.selectedIds, ...currentPageIds])]
    } else {
      // 取消全选当前页面的所有选项
      const currentPageIds = copyAccountOptions.value.map(item => String(item.id))
      copyForm.selectedIds = copyForm.selectedIds.filter(id => !currentPageIds.includes(id))
    }
    updateCopySelectStatus()
  }
  
  // 更新复制选择状态
  const updateCopySelectStatus = () => {
    const currentPageIds = copyAccountOptions.value.map(item => String(item.id))
    const selectedCurrentPageIds = copyForm.selectedIds.filter(id => currentPageIds.includes(id))
    
    if (selectedCurrentPageIds.length === 0) {
      copySelectAll.value = false
      copySelectIndeterminate.value = false
    } else if (selectedCurrentPageIds.length === currentPageIds.length) {
      copySelectAll.value = true
      copySelectIndeterminate.value = false
    } else {
      copySelectAll.value = false
      copySelectIndeterminate.value = true
    }
  }
  
  // 复制弹框的远程搜索账号
  const copyRemoteSearchAccount = (query: string) => {
    console.log(query,'copy query')
    copyAccountKeyword.value = query
    copyAccountCurrentPage.value = 1
    copyFetchAccountOptions()
    
    // 如果搜索关键词为空，显示提示
    if (!query.trim()) {
      console.log('搜索关键词为空，显示所有可用账号')
    }
  }
  
  // 复制弹框获取账号选项
  const copyFetchAccountOptions = async () => {
    copyAccountLoading.value = true
    try {
      const params = {
        account_role_type: "ACCOUNT_ROLE_TYPE_ADVERTISER",
        page_no: copyAccountCurrentPage.value,
        page_size: copyAccountPageSize.value,
        account_id: copyAccountKeyword.value, // 搜索条件
        corporation_name: currentCopyRow.value!.corporation_name
      }    
      const res = await apiGetAccounts(params)
      if (res.list) {
        copyAccountOptions.value = res.list || []
        copyAccountTotal.value = res.total || 0
        // 更新选择状态
        updateCopySelectStatus()
        
        // 如果没有数据，显示友好提示
        if (res.list.length === 0 && copyAccountCurrentPage.value === 1) {
          console.log('当前条件下暂无可用账号数据')
        }
      } else {
        copyAccountOptions.value = []
        copyAccountTotal.value = 0
        console.warn('获取广告主账号列表失败：接口返回数据格式异常')
      }
    } catch (error) {
      console.error('获取广告主账号列表失败：', error)
      copyAccountOptions.value = []
      copyAccountTotal.value = 0
      // 只在非搜索状态下显示错误提示
      if (!copyAccountKeyword.value) {
        ElMessage.warning('获取账号列表失败，请稍后重试')
      }
    } finally {
      copyAccountLoading.value = false
    }
  }
  
  // 复制弹框处理账号分页变化
  const copyHandleAccountPageChange = (page: number) => {
    copyAccountCurrentPage.value = page
    copyFetchAccountOptions()
  }
  
  // 处理复制按钮点击
  const handleCopy = async (row: AdListItem) => {
    // 权限检查
    if (!hasAdvertiserPermission(row)) {
        ElMessage.warning(getPermissionMessage(row))
        return
    }
    
    currentCopyRow.value = row
    copyForm.ad_group_name = `${row.ad_group_name}_复制`
    copyForm.selectedIds = []
    // 重置全选状态
    copySelectAll.value = false
    copySelectIndeterminate.value = false
    // 设置默认投放时间为今天开始，7天后结束
    const today = new Date()
    const nextWeek = new Date()
    nextWeek.setDate(nextWeek.getDate() + 7)
    copyForm.startTime = today
    copyForm.endTime = nextWeek
    copyDialogVisible.value = true
    // 加载账号列表
    copyAccountCurrentPage.value = 1
    copyFetchAccountOptions()
  }
  
  // 确认复制
  const confirmCopy = async () => {
    if (!copyForm.ad_group_name) {
      ElMessage.warning('请输入广告名称')
      return
    }
    if (copyForm.selectedIds.length === 0) {
      ElMessage.warning('请选择要复制到的账号')
      return
    }
    if (!copyForm.startTime) {
      ElMessage.warning('请选择开始时间')
      return
    }
    if (!copyForm.endTime) {
      ElMessage.warning('请选择结束时间')
      return
    }
    const loadingInstance = ElLoading.service({
        lock: true,
        text: '复制中...',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    try {
      copyLoading.value = true
      const response = await copyAd({
        ids: copyForm.selectedIds,
        ad_group_name: copyForm.ad_group_name,
        corporation_name: currentCopyRow.value!.corporation_name,
        ad_group_id: currentCopyRow.value!.ad_group_id,
        ad_account_id: currentCopyRow.value!.ad_account_id,
        account_id: currentCopyRow.value!.account_id,
        begin_date: copyForm.startTime ? formatDate(copyForm.startTime) : undefined,
        end_date: copyForm.endTime ? formatDate(copyForm.endTime) : undefined
      })

      loadingInstance.close()
      
      // 处理复制结果
      console.log(response,'responseresponseresponse')
      const { success, fail, not_in } = response
      
        let message = ''  
        if (success && success.length > 0) {
          console.log('复制成功5')
          message += `<div>复制成功：${success.length} 个账号</div>`
          message += `<div>成功账号ID：${success.join(', ')}</div>`
        }
        
        if (not_in && not_in.length > 0) {
          console.log('无需复制6')
          if (message) message += '<br>'
          message += `<div>无需复制：${not_in.length} 个账号</div>`
          message += `<div>无需复制账号ID：${not_in.join(', ')}</div>`
        }
        
        if (fail && fail.length > 0) {
          console.log('复制失败7')
          if (message) message += '<br>'
          message += `<div>复制失败：${fail.length} 个账号</div>`
          message += `<div>失败账号ID：${fail.join(', ')}</div>`
        }
        
        if (success && success.length > 0 || not_in && not_in.length > 0) {
          console.log('复制成功8')
          ElMessage.success({
            message: message,
            duration: 10000,
            dangerouslyUseHTMLString: true
          })
        } else {
          console.log('复制失败9')
          ElMessage.error({
            message: message || '复制失败',
            duration: 10000,
            dangerouslyUseHTMLString: true
          })
        } 
        copyDialogVisible.value = false
        getLists()
    } catch (error: any) {
      console.error('复制广告失败：', error)
      if(error.fail){
        ElMessage.error({
        message: error.fail.join(',') || '复制广告失败！！！',
        duration: 15000
      })
      }else{
        ElMessage.error({
          message: error.response?.data?.message || '复制广告失败！！！',
          duration: 15000
        })
      }
    } finally {
        loadingInstance.close()
        copyLoading.value = false
    }
  }
  
  // 监听产品列表变化，在编辑时自动匹配marketing_asset_id
  watch(targetAssetOptions, (newOptions) => {
    if (dialogType.value === 'edit' && newOptions.length > 0 && formData.target_asset_id) {
      console.log('产品列表已更新，尝试匹配marketing_asset_id:', formData.target_asset_id)
      nextTick(() => {
        matchMarketingAssetId()
      })
    }
  }, { deep: true })
  
  // 监听营销目的变化
  watch(() => formData.marketing_goal, (newValue, oldValue) => {
    console.log('营销目的变化:', oldValue, '->', newValue)
    if (newValue && newValue !== oldValue && !isCleaning.value) {
      console.log('营销目的发生变化，开始重新加载相关数据')
      
      // 只在新建时清空依赖的选项，编辑时保持选择
      if (dialogType.value === 'add') {
        formData.marketing_target_type = ''
        formData.target_asset_id = ''
        formData.optimization_goal = ''
        marketingTargetTypes.value = {}
        targetAssetOptions.value = []
        optimizationGoals.value = []
      }
      
      // 重置加载状态
      marketingTargetTypeLoading.value = false
      
      // 使用防抖，避免频繁请求
      if (marketingGoalChangeTimer.value) {
        clearTimeout(marketingGoalChangeTimer.value)
      }
      
      marketingGoalChangeTimer.value = setTimeout(() => {
        console.log('开始调用fetchMarketingTargetTypes')
        fetchMarketingTargetTypes()
      }, 300) // 300ms防抖
    }
  })
  
  // 处理产品选择变化
  const handleTargetAssetChange = (value: string) => {
      console.log('产品选择变化:', value)
      if (value) {
          // 确保值是字符串类型
          formData.target_asset_id = String(value)
          
          // 查找选中的产品信息
          const selectedAsset = targetAssetOptions.value.find(
              (asset: TargetAssetOption) => String(asset.marketing_asset_id) === String(value)
          )
          
          if (selectedAsset) {
              console.log('选中的产品信息:', selectedAsset)
              console.log('产品名称:', selectedAsset.marketing_asset_name)
              console.log('产品描述:', selectedAsset.description)
          }
          
          // 重新加载优化目标 - 这里不需要手动调用，因为watch会监听到target_asset_id的变化
          console.log('产品选择变化，优化目标将通过watch自动更新')
      } else {
          formData.target_asset_id = ''
          // 只在新建时清空优化目标
          if (dialogType.value === 'add') {
              formData.optimization_goal = ''
              optimizationGoals.value = []
          }
      }
  }
  
  // 处理营销目的点击
  const handleMarketingGoalClick = (value: MarketingGoal) => {
    // 如果没有选择广告主账号，不允许选择营销目的
    if (!formData.ad_account_id) {
      ElMessage.warning('请先选择广告主账号')
      return
    }
    
    console.log('营销目的点击:', value)
    formData.marketing_goal = value
  }
  
  // 组件卸载时清理定时器
  onUnmounted(() => {
    if (marketingGoalChangeTimer.value) {
      clearTimeout(marketingGoalChangeTimer.value)
      marketingGoalChangeTimer.value = null
    }
    if (targetAssetSearchTimer.value) {
      clearTimeout(targetAssetSearchTimer.value)
      targetAssetSearchTimer.value = null
    }
    if (regionSearchTimer.value) {
      clearTimeout(regionSearchTimer.value)
      regionSearchTimer.value = null
    }
  })
  
  // 权限判断函数
  const hasAdvertiserPermission = (row: AdListItem): boolean => {
    return row.account_auth?.account_role_type === 'ACCOUNT_ROLE_TYPE_ADVERTISER'
  }
  
  // 获取权限提示信息
  const getPermissionMessage = (row: AdListItem): string => {
    if (!row.account_auth?.account_role_type) {
      return '该授权账号ID没有操作权限'
    }
    
    const roleType = row.account_auth.account_role_type
    switch (roleType) {
      case 'ACCOUNT_ROLE_TYPE_ADVERTISER':
        return ''
      case 'ACCOUNT_ROLE_TYPE_AGENCY':
        return '代理商账号，无编辑权限'
      case 'ACCOUNT_ROLE_TYPE_OPERATOR':
        return '运营账号，无编辑权限'
      case 'ACCOUNT_ROLE_TYPE_BUSINESS_MANAGER':
        return '商务管家账号，无编辑权限'
      default:
        return `账号类型：${roleType}，无编辑权限`
    }
  }

  // 自定义人群相关
  const customAudienceType = ref('all') // 'all' | 'target' | 'exclude'
  const customAudienceOptions = ref<CustomAudienceOption[]>([])
  const customAudienceLoading = ref(false)
  const customAudienceKeyword = ref('')

  // 自定义人群提示信息
  const customAudienceTip = computed(() => {
    if (!formData.account_id) {
      return '请先选择广告主账号'
    }
    if (customAudienceLoading.value) {
      return '正在加载自定义人群数据...'
    }
    if (customAudienceOptions.value.length === 0) {
      if (customAudienceKeyword.value) {
        return `未找到包含"${customAudienceKeyword.value}"的自定义人群`
      }
      return '⚠️ 当前账号暂无自定义人群数据，请先创建自定义人群'
    }
    return ''
  })

  // 远程搜索自定义人群
  const remoteSearchCustomAudience = (query: string) => {
    customAudienceKeyword.value = query
    fetchCustomAudienceOptions()
  }

  // 获取自定义人群列表
  const fetchCustomAudienceOptions = async () => {
    //console.log('fetchCustomAudienceOptions called, account_id:', formData.account_id)
    if (!formData.account_id) {
      customAudienceOptions.value = []
      return
    }
    customAudienceLoading.value = true
    try {
      const params = {
        account_id: formData.account_id,
        keyword: customAudienceKeyword.value,
        page: 1,
        limit: 20
      }
      // console.log('请求自定义人群接口参数:', params)
      const res = await get_custom_audience(params)
      // console.log('自定义人群接口返回:', res)
      
      let list = []
      if (Array.isArray(res)) {
        list = res
      } else if (res && Array.isArray(res.data)) {
        list = res.data
      } else if (res && res.lists && Array.isArray(res.lists)) {
        list = res.lists
      }
      
      // 转换为 el-select 需要的格式：audience_id 作为 value，name 作为 label
      customAudienceOptions.value = list.map((item: any) => ({
        id: String(item.audience_id), // value
        name: item.name,              // label
        description: item.name,       // 描述也使用name
        raw: item                     // 保留原始数据
      }))
      
      console.log('转换后的自定义人群选项:', customAudienceOptions.value)
      
      // 检查是否为空数据并给出提示
      if (list.length === 0) {
        if (customAudienceKeyword.value) {
          // 如果有搜索关键词但没找到结果，只在控制台显示
          console.log(`未找到包含"${customAudienceKeyword.value}"的自定义人群`)
        } else {
          // 如果没有搜索关键词且没有数据，显示提示信息
          ElMessage({
            message: '当前账号暂无自定义人群数据，请先创建自定义人群',
            type: 'warning',
            duration: 8000,
            showClose: true
          })
        }
      }
    } catch (error: any) {
      if (error.name === 'CanceledError' || error.code === 'ERR_CANCELED') {
        console.log('自定义人群请求已取消')
        return
      }
      console.error('获取自定义人群列表失败：', error)
      ElMessage.error('获取自定义人群列表失败')
      customAudienceOptions.value = []
    } finally {
      customAudienceLoading.value = false
    }
  }

  // 监听自定义人群类型变化
  watch(customAudienceType, (newVal) => {
    console.log('customAudienceType changed:', newVal, 'account_id:', formData.account_id)
    if (newVal === 'all') {
      formData.custom_audience = []
      formData.excluded_custom_audience = []
      // 清空选项数据，减少内存占用
      customAudienceOptions.value = []
    } else if (newVal === 'target') {
      formData.excluded_custom_audience = []
      // 不自动加载，等用户点击选择框时再加载
    } else if (newVal === 'exclude') {
      formData.custom_audience = []
      // 不自动加载，等用户点击选择框时再加载
    }
  })

  // 监听账号变化时重新获取自定义人群
  watch(() => formData.account_id, (newVal) => {
    // 在编辑加载时跳过执行，避免与handleEditDataLoad冲突
    if (isEditingLoading.value) {
      return
    }

    // 清空自定义人群
      formData.custom_audience = []
      formData.excluded_custom_audience = []
    //   customAudienceType.value = 'all'
 
    console.log('account_id changed:', newVal)
  })

  // 处理自定义人群选择框聚焦事件
  const handleCustomAudienceFocus = () => {
    console.log('自定义人群选择框被点击，开始加载数据')
    // 如果还没有数据且账号ID存在，则加载数据
    if (customAudienceOptions.value.length === 0 && formData.account_id) {
      fetchCustomAudienceOptions()
    }
  }

  // 处理数据分析按钮点击
  const handleDataAnalysis = async (row: AdListItem) => {
    currentAnalysisRow.value = row
    dataAnalysisDialogVisible.value = true
    // 显示加载状态
    dataAnalysisLoading.value = true
    try {
      await fetchDataAnalysis(row.id)
    } catch (error) {
      console.error('数据分析加载失败：', error)
      ElMessage.error('数据分析加载失败')
    } finally {
      dataAnalysisLoading.value = false
    }
  }

  // 获取数据分析数据
  const fetchDataAnalysis = async (id: string) => {
    try {
      const res = await getAdReport({ id })
      dataAnalysisData.value = res
      console.log('数据分析数据:', res)
    } catch (error) {
      console.error('获取数据分析失败：', error)
      ElMessage.error('获取数据分析失败')
      dataAnalysisData.value = null
      throw error // 重新抛出错误，让调用方处理
    }
  }

  // 刷新数据分析
  const refreshDataAnalysis = async () => {
    if (currentAnalysisRow.value) {
      dataAnalysisLoading.value = true
      try {
        await fetchDataAnalysis(currentAnalysisRow.value.id)
      } catch (error) {
        console.error('刷新数据分析失败：', error)
        ElMessage.error('刷新数据分析失败')
      } finally {
        dataAnalysisLoading.value = false
      }
    }
  }

  // 格式化数字
  const formatNumber = (num: number | string | undefined) => {
    if (num === undefined || num === null) return '0'
    const n = Number(num)
    if (isNaN(n)) return '0'
    if (n >= 10000) {
      return (n / 10000).toFixed(1) + '万'
    }
    return n.toLocaleString()
  }

  // 格式化百分比
  const formatPercentage = (num: number | string | undefined) => {
    if (num === undefined || num === null) return '0%'
    const n = Number(num)
    if (isNaN(n)) return '0%'
    return (n * 100).toFixed(2) + '%'
  }

  // 格式化价格
  const formatPrice = (num: number | string | undefined) => {
    if (num === undefined || num === null) return '0.00'
    const n = Number(num)
    if (isNaN(n)) return '0.00'
    return n.toFixed(2)
  }

  // 路由实例
  const router = useRouter()
  
  // 处理编辑创意按钮点击
  const handleEditCreative = async (row: AdListItem) => {
    // 权限检查
    if (!hasAdvertiserPermission(row)) {
      ElMessage.warning(getPermissionMessage(row))
      return
    }
    
    try {
      currentAdForCreative.value = row
      creativeSelectDialogVisible.value = true
      selectedCreative.value = null
      
      // 加载创意列表
      await loadCreativeList(row.ad_group_id)
    } catch (error) {
      console.error('加载创意列表失败：', error)
      ElMessage.error('加载创意列表失败')
    }
  }
  
  // 加载创意列表
  const loadCreativeList = async (adGroupId: string) => {
    creativeListLoading.value = true
    try {
      const params = {
        ad_group_id: adGroupId,
        page_size: 50 // 获取更多创意数据
      }
      
      const response = await apiTencentAdCreativityList(params)
      if (response && response.lists) {
        creativeList.value = response.lists
      } else {
        creativeList.value = []
      }
    } catch (error) {
      console.error('获取创意列表失败：', error)
      ElMessage.error('获取创意列表失败')
      creativeList.value = []
    } finally {
      creativeListLoading.value = false
    }
  }
  
  // 处理创意选择
  const handleCreativeSelect = async (creative: any) => {
    if (creativeJumpLoading.value) return // 防止重复点击
    
    try {
      creativeJumpLoading.value = true
      selectedCreative.value = creative
      
      // 跳转到创意编辑页面
      await router.push({
        path: '/ads/ads/creatives',
        query: {
          id: creative.id,
          dynamic_creative_id: creative.dynamic_creative_id,
          ad_group_id: currentAdForCreative.value.ad_group_id,
          ad_group_name: currentAdForCreative.value.ad_group_name,
          account_id: currentAdForCreative.value.account_id,
          ad_account_id: currentAdForCreative.value.ad_account_id,
          corporation_name: currentAdForCreative.value.corporation_name,
          from_ad_group: 'true',
          edit_mode: 'true'
        }
      })
      
      // 关闭弹框
      creativeSelectDialogVisible.value = false
      ElMessage.success('正在跳转到创意编辑页面...')
    } catch (error) {
      console.error('跳转失败：', error)
      ElMessage.error('跳转失败，请重试')
    } finally {
      creativeJumpLoading.value = false
    }
  }
  
  // 处理新建创意
  const handleCreateNewCreative = async () => {
    if (creativeJumpLoading.value) return // 防止重复点击
    
    try {
      creativeJumpLoading.value = true
      
      // 跳转到创意新增页面
      await router.push({
        path: '/ads/ads/creatives',
        query: {
          ad_group_id: currentAdForCreative.value.ad_group_id,
          ad_group_name: currentAdForCreative.value.ad_group_name,
          account_id: currentAdForCreative.value.account_id,
          ad_account_id: currentAdForCreative.value.ad_account_id,
          corporation_name: currentAdForCreative.value.corporation_name,
          from_ad_group: 'true',
          add_mode: 'true'
        }
      })
      
      // 关闭弹框
      creativeSelectDialogVisible.value = false
      ElMessage.success('正在跳转到创意新增页面...')
    } catch (error) {
      console.error('跳转失败：', error)
      ElMessage.error('跳转失败，请重试')
    } finally {
      creativeJumpLoading.value = false
    }
  }
  
  // 获取创意状态类型
  const getCreativeStatusType = (status: string): 'success' | 'warning' | 'info' | 'danger' => {
    const statusMap: { [key: string]: 'success' | 'warning' | 'info' | 'danger' } = {
      'CREATIVE_SET_APPROVAL_STATUS_NORMAL': 'success',
      'CREATIVE_SET_APPROVAL_STATUS_PENDING': 'warning',
      'CREATIVE_SET_APPROVAL_STATUS_REJECTED': 'danger',
      'CREATIVE_SET_APPROVAL_STATUS_DISAPPROVED': 'danger'
    }
    return statusMap[status] || 'info'
  }
  
  // 获取创意状态文本
  const getCreativeStatusText = (status: string) => {
    const statusTextMap: { [key: string]: string } = {
      'CREATIVE_SET_APPROVAL_STATUS_NORMAL': '正常',
      'CREATIVE_SET_APPROVAL_STATUS_PENDING': '审核中',
      'CREATIVE_SET_APPROVAL_STATUS_REJECTED': '已拒绝',
      'CREATIVE_SET_APPROVAL_STATUS_DISAPPROVED': '未通过'
    }
    return statusTextMap[status] || status
  }
  
  // 格式化创意时间
  const formatCreativeTime = (time: string) => {
    if (!time) return '-'
    return new Date(time).toLocaleString('zh-CN')
  }
  
  // 获取创意行样式
  const getCreativeRowClass = ({ row }: { row: any }) => {
    return selectedCreative.value && selectedCreative.value.id === row.id ? 'selected-row' : ''
  }
  
  // 确认跳转
  const confirmJump = async () => {
    if (creativeJumpLoading.value) return // 防止重复点击
    
    if (currentCreatedAd.value) {
      try {
        creativeJumpLoading.value = true
        
        // 关闭弹框
        creativeJumpDialogVisible.value = false
        
        // 跳转到创意新增页面，并传递广告组信息
        await router.push({
          path: '/ads/ads/creatives',
          query: {
            ad_group_id: currentCreatedAd.value.ad_group_id,
            ad_group_name: currentCreatedAd.value.ad_group_name,
            account_id: currentCreatedAd.value.account_id,
            ad_account_id: currentCreatedAd.value.ad_account_id,
            corporation_name: currentCreatedAd.value.corporation_name,
            from_ad_group: 'true' // 标识来源
          }
        })
        
        ElMessage.success('正在跳转到创意新增页面...')
      } catch (error) {
        console.error('跳转失败：', error)
        ElMessage.error('跳转失败，请重试')
        // 重新打开弹框
        creativeJumpDialogVisible.value = true
      } finally {
        creativeJumpLoading.value = false
      }
    }
  }
  </script>
  
  <style scoped>
  .search-card {
    margin-bottom: 20px;
  }
  
  .operation-area {
    margin-bottom: 20px;
  }
  
  .list-card {
    margin-bottom: 20px;
  }
  
  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
  
  .mx-2 {
    margin: 0 8px;
  }
  
  :deep(.el-card) {
    margin-bottom: 16px;
  }
  
  :deep(.el-form-item) {
    margin-bottom: 16px;
  }
  
  :deep(.el-table) {
    margin-top: 16px;
  }
  
  :deep(.el-pagination) {
    margin-top: 16px;
    justify-content: flex-end;
  }
  
  .region-select {
    display: flex;
    align-items: center;
    margin-bottom: 8px; 
  }
  
  .region-select .el-select {
    margin-right: 8px;
  }
  
  .region-select .el-select:last-child {
    margin-right: 0;
  }
  
  /* 添加表单标题样式 */
  :deep(.form-section-title) {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 24px;
    padding-bottom: 12px;
    border-bottom: 1px solid #ebeef5;
    color: #303133;
  }
  
  :deep(.form-section) {
    margin-bottom: 32px;
  }
  
  :deep(.form-section:last-child) {
    margin-bottom: 0;
  }
  
  /* 添加营销目标类型单选按钮样式 */
  :deep(.el-radio) {
    margin-right: 0;
    padding: 4px 12px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    margin-bottom: 4px;
    white-space: nowrap;
  }
  
  :deep(.el-radio.is-checked) {
    border-color: var(--el-color-primary);
    background-color: var(--el-color-primary-light-9);
  }
  
  :deep(.el-radio__input.is-checked + .el-radio__label) {
    color: var(--el-color-primary);
  }
  
  :deep(.el-select-dropdown__item) {
    padding: 8px 12px;
  }
  
  :deep(.el-select-dropdown__item.selected) {
    color: var(--el-color-primary);
    font-weight: bold;
  }
  
  .marketing-goals {
    width: 100%;
  }
  
  .goal-item {
    min-width: 100px;
  }
  
  .goal-card {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 8px 12px;
    background-color: #f5f7fa;
    border-radius: 4px;
    transition: all 0.3s;
  }
  
  .goal-card:hover {
    background-color: #ecf5ff;
  }
  
  .goal-item.active .goal-card {
    background-color: #ecf5ff;
    border: 1px solid var(--el-color-primary);
    color: var(--el-color-primary);
  }
  
  .goal-item.active :deep(.el-icon) {
    color: var(--el-color-primary);
  }
  
  :deep(.el-icon) {
    font-size: 20px;
    color: #909399;
  }
  
  :deep(.el-form-item__content) {
    width: 100%;
  }
  
  :deep(.product-select-dropdown) {
    max-width: 90vw;
  }
  
  :deep(.el-select-dropdown__item .flex) {
    gap: 8px;
  }
  
  @media screen and (max-width: 1024px) {
    :deep(.el-dialog) {
      width: 95% !important;
      margin: 0 auto;
    }
    
    :deep(.el-form-item__label) {
      margin-bottom: 8px;
    }
  }
  
  :deep(.region-select-dropdown) {
    max-height: 400px;
    overflow-y: auto;
    min-width: 200px;
    white-space: normal;
    word-break: break-all;
  }
  
  :deep(.el-select .el-select__tags) {
    max-height: 80px;
    overflow-y: auto;
    flex-wrap: wrap;
  }
  
  :deep(.el-icon.copy-icon svg) {
    width: 13px !important;
    height: 13px !important;
    font-size: 13px !important;
  }
  
  .age-align-fix :deep(.el-select) {
    align-self: center;
  }
  
  .age-checkbox-group :deep(.el-checkbox) {
    margin-right: 12px;
    margin-bottom: 4px;
  }
  .age-checkbox-group :deep(.el-checkbox__label) {
    font-size: 16px;
  }
  .age-checkbox-group :deep(.el-checkbox__input) {
    transform: scale(1.2);
    margin-right: 6px;
  }
  
  /* 营销目的禁用状态样式 */
  .goal-item.disabled {
    cursor: not-allowed;
    opacity: 0.5;
  }
  
  .goal-item.disabled .goal-card {
    background-color: #f5f7fa;
    border: 1px solid #dcdfe6;
    color: #c0c4cc;
  }
  
  .goal-item.disabled:hover .goal-card {
    background-color: #f5f7fa;
    transform: none;
    box-shadow: none;
  }
  
  .goal-item.disabled :deep(.el-icon) {
    color: #c0c4cc;
  }
  
  /* 禁用按钮样式 */
  :deep(.el-button.is-disabled) {
    color: #c0c4cc !important;
    cursor: not-allowed;
    opacity: 0.6;
  }
  
  :deep(.el-button.is-disabled:hover) {
    color: #c0c4cc !important;
    background-color: transparent !important;
    opacity: 0.6;
  }
  
  /* 操作按钮提示样式 */
  :deep(.el-button[title]) {
    position: relative;
  }
  
  :deep(.el-button[title]:hover::after) {
    content: attr(title);
    position: absolute;
    bottom: 100%;
    left: 50%;
    transform: translateX(-50%);
    background-color: rgba(0, 0, 0, 0.8);
    color: white;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    white-space: nowrap;
    z-index: 1000;
    margin-bottom: 4px;
  }

  /* 自定义人群选择框样式 */
  :deep(.el-form-item__content) {
    width: 100%;
  }

  :deep(.el-select) {
    width: 100%;
  }

  :deep(.el-select .el-input__wrapper) {
    width: 100%;
  }

  :deep(.el-select .el-select__tags) {
    max-height: 80px;
    overflow-y: auto;
    flex-wrap: wrap;
  }

  /* 确保自定义人群选择框不被挤压 */
  .custom-audience-select {
    width: 100%;
    min-width: 300px;
  }

  :deep(.custom-audience-select .el-select) {
    width: 100%;
  }

  /* 自定义人群提示信息样式 */
  .custom-audience-tip {
    margin-top: 8px;
  }

  .custom-audience-tip :deep(.el-alert__title) {
    font-size: 13px;
    line-height: 1.4;
  }

  .custom-audience-tip :deep(.el-alert__icon) {
    font-size: 16px;
  }

  @media screen and (max-width: 1024px) {
    :deep(.el-dialog) {
      width: 95% !important;
      margin: 0 auto;
    }
    
    :deep(.el-form-item__label) {
      margin-bottom: 8px;
    }
  }
  
  /* 自定义人群提示信息样式 */
  .custom-audience-tip {
    margin-top: 8px;
  }
  
  .custom-audience-tip :deep(.el-alert__title) {
    font-size: 13px;
    line-height: 1.4;
  }
  
  .custom-audience-tip :deep(.el-alert__icon) {
    font-size: 16px;
  }
  
  /* 自定义人群选择框空数据提示样式 */
  :deep(.custom-audience-select .el-select-dropdown__empty) {
    color: #e6a23c;
    font-weight: 500;
    font-size: 14px;
    padding: 16px 12px;
    background-color: #fdf6ec;
    border-radius: 4px;
    margin: 8px;
    text-align: center;
  }
  
  :deep(.custom-audience-select .el-select-dropdown__empty::before) {
    content: "⚠️";
    display: block;
    font-size: 20px;
    margin-bottom: 8px;
  }

  /* 数据分析弹框样式 */
  .data-analysis-content {
    padding: 20px 0;
  }

  .analysis-header {
    text-align: center;
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 1px solid #ebeef5;
  }

  .analysis-title {
    font-size: 24px;
    font-weight: bold;
    color: #303133;
    margin: 0 0 8px 0;
  }

  .analysis-subtitle {
    font-size: 14px;
    color: #909399;
    margin: 0;
  }

  .analysis-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
  }

  .analysis-card {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 12px;
    padding: 20px;
    color: white;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
    transition: transform 0.3s ease, box-shadow 0.3s ease;
    position: relative;
    overflow: hidden;
  }

  .analysis-card:nth-child(2) {
    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  }

  .analysis-card:nth-child(3) {
    background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  }

  .analysis-card:nth-child(4) {
    background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
  }

  .analysis-card:nth-child(5) {
    background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
  }

  .analysis-card:nth-child(6) {
    background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
  }

  .analysis-card:nth-child(7) {
    background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
  }

  .analysis-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
  }

  .card-header {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
  }

  .card-icon {
    font-size: 20px;
    margin-right: 8px;
    opacity: 0.9;
  }

  .card-title {
    font-size: 14px;
    font-weight: 500;
    opacity: 0.9;
  }

  .card-value {
    font-size: 28px;
    font-weight: bold;
    margin-bottom: 8px;
    line-height: 1;
  }

  .card-trend {
    font-size: 12px;
    opacity: 0.8;
  }

  .trend-up {
    color: #67c23a;
  }

  .trend-down {
    color: #f56c6c;
  }

  .analysis-summary {
    background: #f8f9fa;
    border-radius: 8px;
    padding: 20px;
    margin-top: 20px;
  }

  .analysis-summary h4 {
    margin: 0 0 15px 0;
    color: #303133;
    font-size: 16px;
    font-weight: 600;
  }

  .summary-content {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 10px;
  }

  .summary-content p {
    margin: 0;
    color: #606266;
    font-size: 14px;
    line-height: 1.6;
  }

  .no-data {
    text-align: center;
    padding: 40px 20px;
  }

  .loading-content {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 300px;
    padding: 40px 20px;
  }

  .loading-spinner {
    text-align: center;
  }

  .loading-spinner .el-icon {
    font-size: 32px;
    color: #409eff;
    margin-bottom: 16px;
  }

  .loading-spinner p {
    margin: 0;
    color: #606266;
    font-size: 14px;
  }

  @media (max-width: 768px) {
    .analysis-grid {
      grid-template-columns: 1fr;
    }
    
    .summary-content {
      grid-template-columns: 1fr;
    }
  }

  /* 操作按钮样式 */
  .operation-buttons {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    justify-content: center;
    align-items: center;
    min-height: 32px;
    padding: 4px 0;
  }

  .operation-buttons .el-button {
    margin: 0;
    padding: 4px 8px;
    font-size: 14px;
    font-weight: 500;
    line-height: 1.4;
    white-space: nowrap;
    min-width: auto;
    height: auto;
    border: none;
    background: transparent;
  }

  .operation-buttons .el-button:hover {
    background-color: rgba(64, 158, 255, 0.1);
    border-radius: 4px;
  }

  .operation-buttons .el-button + .el-button {
    margin-left: 0;
  }

  /* 不同颜色按钮的悬停效果 */
  .operation-buttons .el-button--primary:hover {
    background-color: rgba(64, 158, 255, 0.1);
  }

  .operation-buttons .el-button--success:hover {
    background-color: rgba(103, 194, 58, 0.1);
  }

  .operation-buttons .el-button--danger:hover {
    background-color: rgba(245, 108, 108, 0.1);
  }

  /* 确保操作列在移动端也能正常显示 */
  @media (max-width: 1200px) {
    .operation-buttons {
      flex-direction: column;
      gap: 4px;
      align-items: stretch;
    }
    
    .operation-buttons .el-button {
      width: 100%;
      text-align: center;
      padding: 6px 8px;
      font-size: 13px;
    }
  }

  /* 表格操作列样式优化 */
  :deep(.el-table .el-table__cell) {
    padding: 8px 0;
  }

  :deep(.el-table .operation-buttons) {
    padding: 4px 0;
  }

  /* 确保按钮文字不被截断 */
  :deep(.el-table .operation-buttons .el-button span) {
    display: inline-block;
    max-width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  /* 创意跳转弹框样式 */
  .jump-content {
    padding: 20px 0;
  }

  .jump-content p {
    margin-bottom: 16px;
    color: #606266;
    line-height: 1.6;
  }

  .jump-content ul {
    background: #f8f9fa;
    border-radius: 8px;
    padding: 16px;
    margin: 16px 0;
  }

  .jump-content li {
    margin-bottom: 8px;
    color: #303133;
    font-size: 14px;
  }

  .jump-content li:last-child {
    margin-bottom: 0;
  }

  .jump-content li strong {
    color: #409eff;
    font-weight: 600;
  }
  
  /* 创意选择弹框样式 */
  .creative-select-content {
    max-height: 600px;
    overflow-y: auto;
  }
  
  .creative-list {
    margin-top: 16px;
  }
  
  .creative-list .no-data {
    text-align: center;
    padding: 40px 0;
    color: #999;
  }
  
  .selected-row {
    background-color: #f0f9ff !important;
  }
  
  .selected-row:hover {
    background-color: #e0f2fe !important;
  }
  
  /* 创意表格样式 */
  :deep(.creative-list .el-table) {
    border-radius: 8px;
    overflow: hidden;
  }
  
  :deep(.creative-list .el-table th) {
    background-color: #f8f9fa;
    color: #606266;
    font-weight: 600;
  }
  
  :deep(.creative-list .el-table td) {
    padding: 12px 0;
  }
  
  :deep(.creative-list .el-table .el-button) {
    padding: 6px 12px;
    font-size: 12px;
  }
  </style>
  